2014-02-10 145 views
6

假設我有兩個列表:如何將兩個列表合併到python中的一列列中?

t1 = ["abc","def","ghi"] 
t2 = [1,2,3] 

我如何可以合併使用它蟒蛇,使輸出列表將是:

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

我不想重複條目。

+2

''[...]'是一個列表,'(...)'是一個元組。 – Christian

+0

對不起基督徒,並感謝您的更正 – Madhusudan

回答

10

在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)] 
>>> 
+0

可能是錯的,但我認爲你第一次閱讀正確。我認爲壓縮列表是OP需要的,你寫的是OP的嘗試產生的內容,但OP「[不需要重複輸入」。 – DSM

+0

@DSM - 就是這樣。我需要另一杯咖啡...... – iCodez

5

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

如果你不想重複的項目,你不在乎有關訂單,用一套:

>>> 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)] 
相關問題