简体   繁体   English

在列表中加入元组

[英]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 : 这是一个使用zipitertools.chain的简单替代方案:

from itertools import chain
[list(chain.from_iterable(i)) for i in zip(*mylist)]
# [['a', 'b', 'c', 'd'], [1, 2, 3]]

zip works as well: zip也可以:

tuple(map(lambda x: x[0]+x[1],  zip(mylist[0], mylist[1])))

Code : 代码

mylist = [(['a', 'b'], [1, 2]), (['c', 'd'], [3])]

print(tuple(map(lambda x: x[0]+x[1],  zip(mylist[0], mylist[1]))))
# (['a', 'b', 'c', 'd'], [1, 2, 3])

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

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