[英]Join tuples inside list
I have: 我有:
mylist = [(['a', 'b'], [1, 2]), (['c', 'd'], [3])]
I need one list with the letters and one with the numbers, like this: 我需要一个包含字母的列表和一个包含数字的列表,像这样:
(['a', 'b', 'c', 'd'], [1, 2, 3])
I have made some efforts, but I could just get one list with the letters, not both: 我做了一些努力,但是我只能得到一个包含字母的列表,而不是两个都包含:
answer = [item for sublist in mylist for item in sublist[0]]
#returns ['a', 'b', 'c', 'd']
answer = [[item for sublist in mylist for item in sublist[i]] for i in range(2)]
只需要遍历您的子列表即可:)
Here's a simple alternative using zip
and itertools.chain
: 这是一个使用zip
和itertools.chain
的简单替代方案:
from itertools import chain
[list(chain.from_iterable(i)) for i in zip(*mylist)]
# [['a', 'b', 'c', 'd'], [1, 2, 3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.