在python中,如何将两个列表合并成一个列序列?

2024-04-18 09:50:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个列表:

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)]

我不想重复输入。


Tags: in程序列表fordeft1abcprint
2条回答

使用邮编:

>>> 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' 

如果不希望重复项目,并且不关心顺序,请使用集合:

>>> 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)])

如果要按顺序进行uniquify:

>>> 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)]

在Python 2.x中,您只需使用^{}

>>> t1 = ["abc","def","ghi"]
>>> t2 = [1,2,3]
>>> zip(t1, t2)
[('abc', 1), ('def', 2), ('ghi', 3)]
>>>

但是,在Python 3.x中,zip返回一个zip对象(它是一个iterator)而不是一个列表。这意味着您必须通过将结果放入^{}来显式地将结果转换为列表:

>>> 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)]
>>>

相关问题 更多 >