如何在python中将两个列表合并为一系列列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21684770/
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
How to merge two lists into a sequence of columns in python?
提问by Madhusudan
Suppose I have two lists:
假设我有两个列表:
t1 = ["abc","def","ghi"]
t2 = [1,2,3]
How can I merge it using python so that output list will be:
如何使用 python 合并它,以便输出列表为:
t = [("abc",1),("def",2),("ghi",3)]
The program that I have tried is:
我试过的程序是:
t1 = ["abc","def"]
t2 = [1,2]
t = [ ]
for a in t1:
for b in t2:
t.append((a,b))
print t
Output is:
输出是:
[('abc', 1), ('abc', 2), ('def', 1), ('def', 2)]
I don't want repeated entries.
我不想重复输入。
采纳答案by Madhusudan
In Python 2.x, you can just use zip:
在 Python 2.x 中,您可以只使用zip:
>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>
However, in Python 3.x, zipreturns a zip object (which is an iterator) instead of a list. This means that you will have to explicitly convert the results into a list by putting them in list:
但是,在 Python 3.x 中,zip返回一个 zip 对象(它是一个迭代器)而不是一个列表。这意味着您必须将结果显式地转换为列表list:
>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
<zip object at 0x020C7DF0>
>>> list(zip(t1, t2))
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>
回答by dawg
Use zip:
使用邮编:
>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> list(zip(t1,t2))
[('abc', 1), ('def', 2), ('ghi', 3)]
# Python 2 you do not need 'list' around 'zip'
If you do not want repeated items, and you do not care about order, use a set:
如果您不想要重复的项目,并且您不关心顺序,请使用集合:
>>> l1 = ["abc","def","ghi","abc","def","ghi"]
>>> l2 = [1,2,3,1,2,3]
>>> set(zip(l1,l2))
set([('def', 2), ('abc', 1), ('ghi', 3)])
If you want to uniquify in order:
如果要按顺序统一:
>>> seen=set()
>>> [(x, y) for x,y in zip(l1,l2) if x not in seen and (seen.add(x) or True)]
[('abc', 1), ('def', 2), ('ghi', 3)]

