假设我有两个列表:
t1 = ["abc","def","ghi"]
t2 = [1,2,3]
我如何使用python合并它,以便输出列表为:
t = [("abc",1),("def",2),("ghi",3)]
我尝试过的程序是:
t1 = ["abc","def"]
t2 = [1,2]
t = [ ]
for a in t1:
for b in t2:
t.append((a,b))
print t
输出为:
[('abc', 1), ('abc', 2), ('def', 1), ('def', 2)]
我不想重复输入。
在Python 2.x中,您可以使用zip
:
>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>
但是,在Python 3.x中,zip
返回的是一个zip对象(它是一个iterator)而不是一个列表。这意味着您必须通过将结果放入以下位置来将结果显式转换为列表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)]
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句