1

Does anybody know the syntax of turning a list of lists into something that looks like what I have drawn below?

The list of lists would look like so:

list = [0, [~, ~, ~], 1, [~, ~, ~], 2, [~, ~, ~] ]

And this is the desired output:

0 ~ ~ ~
1 ~ ~ ~
2 ~ ~ ~   

I've seen other people ask a similar question however their sub-lists only had one element, and there were no integer elements in front of each sub-list either, and so they used the following in order to obtain the result that I need:

"\n".join(item[0] for item in list)

I'm not sure how to manipulate the above line of code to solve my specific problem. I tried changing

item[0] to item[0:len(sub_list)] 

and many other things but nothing has worked. (I'm quite inexperienced with Python)

Any help would be greatly appreciated. Thanks.

Sandi Milicevic
  • 23
  • 1
  • 1
  • 4

8 Answers8

6

One can always use explicit iteration by twos:

el = [0, ['~', '~', '~'], 1, ['~', '~', '~'], 2, ['~', '~', '~'] ]
for i in range(0, len(el), 2):
    print el[i], " ".join(el[i+1])

I cannot presently think of anything cleverer.

zwol
  • 135,547
  • 38
  • 252
  • 361
2

Not as clever or concise as the other answers, but definitely readable:

# This function is taken from 
# http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

my_list = [0, ['~', '~', '~'], 1, ['~', '~', '~'], 2, ['~', '~', '~'] ]

paired = chunks(my_list, 2)

for index, lst in paired:
    print index, ' '.join(lst)
Jong Bor Lee
  • 3,805
  • 1
  • 24
  • 27
1

First off, let's correct that definition:

lst = [0, ['~', '~', '~'], 1, ['~', '~', '~'], 2, ['~', '~', '~']]

Please, never use list as an identifier name. It shadows the builtin function list.

To make this easier to handle, convert it to a simple list of lists:

lst = [[lst[i]] + lst[i+1] for i in xrange(0, len(lst), 2)]

Then join that:

print "\n".join([" ".join(map(str, x)) for x in lst])
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • There is no need to use the square-brackets `[]` inside the `join()` method. You can pass it as a generator expression – juliomalegria Feb 04 '12 at 22:28
  • `join` has to build a list anyway (to calculate the length of the resulting string), so it is usually faster to use the list comprehension instead of the generator expression. – Reinstate Monica Feb 04 '12 at 22:58
  • @WolframH really? why does it need to calculate the length? do you have some link with the source code? – juliomalegria Feb 04 '12 at 23:04
  • It has to allocate memory for the string. I didn't look at the source code, but it is stated quite often. Look here, for example: http://stackoverflow.com/questions/9143506/whats-the-best-way-to-convert-an-array-of-ints-into-a-string/9143515#comment11494997_9143515 . – Reinstate Monica Feb 04 '12 at 23:30
  • I'll take Raymond Hettinger's word for it. Put the `[]` back in. – Fred Foo Feb 04 '12 at 23:31
0

You could use a comprehension over the indices up to the length of the list

'\n'.join('%s %s' % (list[2 * i], list[2 * i + 1]) for i in [0:len(list)/2])
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
0

First, I'm using zip() to group your list in groups of two. Then, I'm iterating over the sublist, and using join() to join its elements with a whitespace, appeding it to the first element, and finally, joining all lines with a breakline (\n).

>>> my_list = [0, [11, 1.2, 'str1'], 1, [21, 2.2, 'str2'], 2, [31, 3.2, 'str3'] ]
>>> it = iter(my_list)
>>> my_str = '\n'.join((str(x) + ' ' + ' '.join(str(y) for y in l)) for x, l in zip(it, it))
>>> print my_str
0 11 1.2 str1
1 21 2.2 str2
2 31 3.2 str3

This solution will work with any kind of type in your list and sublists.

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
0

If your list really has that exact structure (non-list element in even positions, list element in odd positions) you could do this:

def pairs(l):
    i = iter(l)
    while 1:
        yield (i.next(), i.next())
print '\n'.join(['%s %s' % (f, ' '.join(s)) for f, s in pairs(list)])
ben w
  • 2,490
  • 14
  • 19
0

You could iterate over the list in chunks (two items at a time) using standard "grouper" idiom:

L = [0, ['~', '~', '~'], 1, ['~', '~', '~'], 2, ['~', '~', '~']]
print('\n'.join("%s %s" % (i, ' '.join(lst)) for i, lst in zip(*[iter(L)]*2)))
Output
0 ~ ~ ~
1 ~ ~ ~
2 ~ ~ ~
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

Using no index and doing no creation of list nor sublist:

lst = [0, ['~', '~', '~'], 1, ['~', 889, '~'], 2, ['~', '~', ('a','b')], 3, ['#', '#'] ]

it = iter(lst)
print '\n'.join( '%s %s' % (x,' '.join(str(u) for u in next(it))) for x in it)

result

0 ~ ~ ~
1 ~ 889 ~
2 ~ ~ ('a', 'b')
3 # #
eyquem
  • 26,771
  • 7
  • 38
  • 46