简体   繁体   中英

splitting list into sublist python

Here is a simple question from a python beginner:

I have a list with sublists: [[1,2,3],['a','b','c']]

I want [1,2,3],['a','b','c']

I tried:

M = [[1,2,3],['a','b','c']]
for item in M:
    print(item)

[1,2,3]

['a','b','c']

But I don't want to use print, and I need to nest the result [1,2,3],['a','b','c'] into another loop.

I tried searching the site for similar question but can't seem to find an answer that I can follow. Could you guys help me? Thanks!

Noticing your comment I have adjusted my answer with my attempt to deliver what you wanted. There are two options, option 1 with the dictionary will work with varying lengths of sublists

from collections import defaultdict

M = [[1,2,3],['a','b','c']]
d = defaultdict(list)
for sublist in M:
    for i,e in enumerate(sublist):
        d[i].append(e)
d = ["".join(str(e) for e in d[i]) for i in range(len(d))]
print (d)

#bonus alternative solution using zip()
d2 = ["".join(str(e) for e in tuple_) for tuple_ in zip(*M)]
print (d2)

Both print:

['1a', '2b', '3c']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM