简体   繁体   English

将列表拆分为子列表python

[英]splitting list into sublist python

Here is a simple question from a python beginner:这是一个来自python初学者的简单问题:

I have a list with sublists: [[1,2,3],['a','b','c']]我有一个包含子列表的列表:[[1,2,3],['a','b','c']]

I want [1,2,3],['a','b','c']我想要 [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.但是我不想使用打印,我需要将结果 [1,2,3],['a','b','c'] 嵌套到另一个循环中。

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有两个选项,带有字典的选项 1 将适用于不同长度的子列表

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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