0

I'm trying to make two lists of the sort:

list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]

into

list_both= ["onetothree",1,2,3,"fourtosix",4,5,6...]

This is just a way to describe my problem. I need to do this with all the elements in list_numbers & list_letters. The number or elements in list_numbers will always be dividable by the amount of elements in list_letters so theres no need to worry about "crooked data".

After searching for a good three hours, trying with many different kinds of "for" and "while" loops and only getting python 2.x questions, bad results and syntax errors, I thought I'd maybe deserve to post this question.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
Flowdorio
  • 157
  • 1
  • 13

2 Answers2

0

Hacky, but it'll get the job done

>>> list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]
>>> list(itertools.chain.from_iterable(zip(list_letters, *zip(*[list_numbers[i:i+3] for i in range(0, len(list_numbers), 3)]))))
['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12]

Or, the cleaner version:

>>> answer = []
>>> i = 0
>>> for letter in list_letters:
...     answer.append(letter)
...     for j in range(3):
...         answer.append(list_numbers[i+j])
...     i += j+1
... 
>>> answer
['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12]

Of course, if you don't have sufficiently many entries in list_numbers, you this will burn you

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • I love you. Another problem that I've been biting my nails bloody over is how to get them all (from one list) to become a series of lists, preferably with unique names. E.g ['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12] to list1 = ['onetothree', 1, 2, 3] list2 = ['fourtosix', 4, 5, 6] The listnames 'listx' needs to be able to loop infinitely, so I need unique names over them. Any idea how to do this? – Flowdorio Aug 02 '13 at 00:18
  • I will always have sufficiently many entries in list_numbers. Thank you for the clean version. – Flowdorio Aug 02 '13 at 00:19
  • There's a lot of love here at SO :) You can create variables with distinct names on-the-fly (actually you can, with `eval`, etc, but you shouldn't). Easiest way is to [split `answer` into even sized chunks](http://stackoverflow.com/q/312443/198633). If that doesn't work, post another question and I (or someone else) will help out ;] – inspectorG4dget Aug 02 '13 at 00:22
0

try this:

list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]
list_both=[]
c=1
for n in range(len(list_letters)):
        list_both.append(list_letters[n])
        list_both[c+n:c+n]=list_numbers[c-1:c+2]
        c+=3
print(list_both)
Z3r0n3
  • 37
  • 4