2014-03-26 85 views
3

我需要合併兩個元組列表,預期結果是兩個列表之間的某種相交,我已經有了DUMB解決方案。
列表1在元組的最後一個元素中具有不完整的值。
列表2具有元組列表1不具備和擁有的元組與完整的價值
結果...嗯 好,例如,在最好的描述:在Python中合併元組列表

 
l1 = [('4',), ('6',)] 
l2 = [('3', '1'), ('4', '23'), ('6', '34')] 

#my dumb solution 
def mymerge(l1,l2): 
    l3 = [] 
    for x in l2: 
     if x[0] in [ y[0] for y in l1 ]: 
      l3.append(x) 
    return l3 

result = mymerge(l1,l2) 
#result is what expected-> [('4','23'),('6','34')] 

我的問題:旁邊 什麼其他的解決辦法我啞巴解決方案?
真的很好奇,
TNX

回答

3

一個list comprehension應該工作:

result = [ l for l in l2 if (l[0],) in l1] 

同樣,你可以使用內置的filter功能

result = filter(lambda x: (x[0],) in l1, l2) 
+0

導致一個空列表 – EdChum

+1

我的編輯解決了該問題 – jmetz

+0

是的這個作品(使用元組的比較需要)現在 – EdChum

2

使用itertools.chain.from_iterablel2作爲字典更好,因爲

  1. 我們不必產生中間元組/列出

  2. 我們將能夠做一定時間內查找,因爲我們使用的是dict


l2 = dict(l2) 
from itertools import chain 
print [(item, l2.get(item)) for item in chain.from_iterable(l1)] 
# [('4', '23'), ('6', '34')] 
0
In [47]: l1 = [('4',), ('6',)] 

In [48]: l2 = [('3', '1'), ('4', '23'), ('6', '34')] 

In [49]: la = [l[0] for l in l1] 

In [50]: la 
Out[50]: ['4', '6'] 

In [51]: [l for l in l2 if l[0] in la] 
Out[51]: [('4', '23'), ('6', '34')] 
1

組查找必須要快:

>>> [ y for y in l2 if y[0] in set(*zip(*l1))] 
[('4', '23'), ('6', '34')] 
>>>