在 Python 中,如何将元组列表加入一个列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15269161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
in Python, How to join a list of tuples into one list?
提问by LWZ
Following on my previous question How to group list items into tuple?
继我之前的问题如何将列表项分组为元组?
If I have a list of tuples, for example
例如,如果我有一个元组列表
a = [(1,3),(5,4)]
How can I unpack the tuples and reformat it into one single list
如何解包元组并将其重新格式化为一个列表
b = [1,3,5,4]
I think this also has to do with the iterfunction, but I really don't know how to do this. Please enlighten me.
我认为这也与iter功能有关,但我真的不知道该怎么做。请赐教。
采纳答案by Volatility
b = [i for sub in a for i in sub]
That will do the trick.
这样就行了。
回答by danodonovan
import itertools
b = [i for i in itertools.chain(*[(1,3),(5,4)])]
回答by Schuh
Just iterate over the list a and unpack the tuples:
只需遍历列表 a 并解压元组:
l = []
for x,y in a:
l.append(x)
l.append(y)
回答by NPE
In [11]: list(itertools.chain(*a))
Out[11]: [1, 3, 5, 4]
If you just need to iterate over 1, 3, 5, 4, you can get rid of the list()call.
如果您只需要迭代1, 3, 5, 4,则可以摆脱list()调用。
回答by NPE
Another way:
其它的办法:
a = [(1,3),(5,4)]
b = []
for i in a:
for j in i:
b.append(j)
print b
This will only handle the tuples inside the list (a) tho. You need to add if-else statements if you want to parse in loose variables too, like;
这只会处理列表 (a) 中的元组。如果您也想解析松散变量,则需要添加 if-else 语句,例如;
a = [(1,3),(5,4), 23, [21, 22], {'somevalue'}]
b = []
for i in a:
if type(i) == (tuple) or type(i) == (list) or type(i) == (set):
for j in i:
b.append(j)
else:
b.append(i)
print b

