ronnie
ronnie

Reputation: 1839

Python: print list of list in a specified format

I have a list of list l = [['a','b', 'c'], 'd','e', ['f', 'g']]. It is not always necessary that list elements are going to be alphabets.

Now, I used the below code:

>>> index =1
>>> for i in l:
...     if isinstance(i, list):
...             for j in i :
...                     print index, j
...                     index = index + 1
...     else:
...             print index, i
...             index = index + 1
... 
1 a
2 b
3 c
4 d
5 e
6 f
7 g

You can see the format in which I have printed out the result.

Another example:

l = [['aaa','bbb','xxx'], 'ddd']

Output = 

1 aaa
2 bbb
3 xxx
4 ddd

My question is there any better way to do this or any built-in function in python.

PS: Lists will be only 1 level nested. So, [ [a, [b,c] ], d, e ] is not a possibility.

Upvotes: 3

Views: 421

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 88977

You can do this very easily with itertools.chain.from_iterable() and enumerate():

>>> import itertools
>>> l = [['a','b', 'c'], 'd','e', ['f', 'g']]
>>> for index, value in enumerate(itertools.chain.from_iterable(l), 1):
...     print(index, value)
... 
1 a
2 b
3 c
4 d
5 e
6 f
7 g

Edit: As mgilson pointed out, this doesn't work well with multi-character strings as elements at the top level. I would argue the best solution then is to use a generator as he does in his answer, however, I would argue that the string is the special case, not the list, so I would reverse the logic:

def flatten(seq):
    for item in seq:
        if not isinstance(item, str): #Use `basestring` in 2.x
            yield from item
            #For Python <3.3
            #for subitem in item:
            #    yield subitem
        else:
            yield item

Upvotes: 7

mgilson
mgilson

Reputation: 309841

I would create a generator to flatten the list:

def flatten(lst):
   for i in lst:
       if(isinstance(i,list)):
          for x in i:
              yield x
       else:
           yield x

Then I would use enumerate for the printing:

for idx,item in enumerate(flatten(lst),1):
    print idx,item

Upvotes: 6

Related Questions