这是一个来自python初学者的简单问题:
我有一个包含子列表的列表:[[1,2,3],['a','b','c']]
我想要[1,2,3],['a','b','c']
我试过了:
M = [[1,2,3],['a','b','c']]
for item in M:
print(item)
[1,2,3]
['a','b','c']
但我不想使用print,我需要将结果[1,2,3],['a','b','c']嵌套到另一个循环中。
我尝试在网站上搜索类似的问题,但似乎无法找到我可以遵循的答案。你们能帮助我吗?谢谢!
答案 0 :(得分:1)
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']