[英]Python: Compare a list and list of tuples
我有一個列表如下所示:
z = [('Anna Smith', 'IN1'), ('John', 'IN2'), ('Matt Andrew', 'IN3'), ('Smith', 'IN4')]
另一個清單:
c = ['Anna Smith', 'John', 'Anna', 'Smith']
我想要以下輸出:
o = ['Anna Smith|IN1', 'John|IN2', 'Smith|IN4']
我試過以下代碼:
for s, s_inc in z:
for word in c:
if word.lower() in s.lower():
o.append("%s|%s"%(word, s_inc))
但上面給出了輸出:
o = ['Anna Smith|IN1', 'Anna|IN1', 'Smith|IN1', 'John|IN2', 'Smith|IN4']
我怎樣才能得到我想要的東西?
列表理解是這種類型的過濾/列表操作問題的優雅方法。
理解包括三個部分:
- 首先,結果是在+'|'+ b中構造的
- 其次,a和b被分配給列表z中的每個2元組中的第一和第二元素
- 第三,我們過濾了必須是列表c的成員的條件
print [a+'|'+b for a,b in z if a in c]
# Prints ['Anna Smith|IN1', 'John|IN2', 'Smith|IN4']
從你的例子,似乎你正在尋找一個精確匹配 ,因此就使用==
而不是in
:
for s, s_inc in z:
for word in c:
if word == s:
o.append("%s|%s"%(word, s_inc))
或者更短,作為單個列表理解:
o = ["%s|%s"%(s, s_inc) for s, s_inc in z if s in c]
在此之后, o
是['Anna Smith|IN1', 'John|IN2', 'Smith|IN4']
嘗試這個:
z = [('Anna Smith', 'IN1'), ('John', 'IN2'), ('Matt Andrew', 'IN3'), ('Smith', 'IN4')]
c = set(['Anna Smith', 'John', 'Anna', 'Smith'])
o = [
'|'.join([name, code]) for name, code in z if name in c
]
我會做c
一套 ,用於快速固定時間的測試:
c_set = {w.lower() for w in c}
我對這些單詞進行了較低的設置,以便在不區分大小寫的情況下輕松測試成員資格。
然后使用:
for s, s_inc in z:
if s.lower() in c_set:
o.append('|'.join([s, s_inc]))
甚至:
o = ['|'.join([s, s_inc]) for s, s_inc in z if s.lower() in c_set]
用列表理解產生整個列表。
演示:
>>> z = [('Anna Smith', 'IN1'), ('John', 'IN2'), ('Matt Andrew', 'IN3'), ('Smith', 'IN4')]
>>> c = ['Anna Smith', 'John', 'Anna', 'Smith']
>>> c_set = {w.lower() for w in c}
>>> ['|'.join([s, s_inc]) for s, s_inc in z if s.lower() in c_set]
['Anna Smith|IN1', 'John|IN2', 'Smith|IN4']
>>> z = [('Anna Smith', 'IN1'), ('John', 'IN2'), ('Matt Andrew', 'IN3'), ('Smith', 'IN4')]
>>> c = ['Anna Smith', 'John', 'Anna', 'Smith']
>>> ['|'.join([i,x[1]]) for x in z for i in c if x[0]==i]
['Anna Smith|IN1', 'John|IN2', 'Smith|IN4']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.