Home > OS >  how to convert list of list to string format (unable to find a way to extract the elements in List o
how to convert list of list to string format (unable to find a way to extract the elements in List o

Time:02-21

I would like to convert the following list: x = [[a,b,c,d],[c,d,e,f]]

to 'abcdcdef'

thanks for your help

CodePudding user response:

Do like this:

[ item for innerlist in outerlist for item in innerlist ]

Turning that directly into a string with separators:

','.join(str(item) for innerlist in outerlist for item in innerlist)

Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:

for innerlist in outerlist:
for item in innerlist:
    ...

CodePudding user response:

You can also try these two methods to combine :

data = [['a','b','c','d'],['c','d','e','f']]

Method #1:

from functools import reduce
p = reduce(lambda x, y : ''.join(x)   ''.join(y), data)
print(p)

Method #2:

q = ''.join(list(map(''.join, data)))
print(q)

Other method is to loop over innerlist and join() method. Thanks

  • Related