[英]How do I compare two lists of diffrent sizes, find matches and return the indices of those matches in both lists
[英]Return indices of string and substring matches in lists
我有兩個列表,一個包含人們姓氏的列表,另一個包含類似數據的列表。 我已經使用any()
來匹配這兩個列表和 output 匹配。
提供的示例數據,實際列表包含數千個條目。
matchers = ['Balle', 'Jobson', 'Watts', 'Dallow', 'Watkins']
full_name = ['Balle S & R', 'Donald D & S', 'Watkins LTD', 'Balle R & R', 'Dallow K & C']
matching = [s for s in full_name if any(xs in s for xs in matchers)]
print(matching)
我想返回每個匹配項的索引。對於上面的示例,理想的 output 將是:
[0, 0], [4, 2], [0, 3], [3, 4]
我努力了:
print([[i for i in range(len(full_name)) if item1 == full_name[i]] for item1 in matchers])
但這會返回一個空的 arrays 列表。 實際上,我的列表包含數千個條目。 當匹配的數據不完全相同時,是否可以找到匹配的索引?
您可以使用“matcher IN name”而不是“==”。
解釋: enumerate() 通過列表幫助我 go 並為列表中的每個值返回 (index,value)。 因此,“index1”將“matcher”的索引存儲在“matchers”列表中。 類似地,“index2”是“name”在 full_name 中的索引。
然后,我檢查“匹配器”是否是“名稱”的 substring。 如果這是真的,那么我會將匹配器索引和名稱索引添加到最終列表中。
試運行:假設 index1=0,matcher="Balle",那么我將遍歷 full_name 中的所有值。 假設 index2=0,name="Balle S & R"。 然后,我的 if 檢查為真,因為“Balle”是“Balle S & R”的 substring。 所以,我將 append [index1, index2] 這是我的最終列表中的 [0,0]。 如果匹配器不是 substring,那么我忽略這對並繼續前進。
這是使用循環的工作代碼。
matches = []
#Loop through each value in matchers and store (index, value)
for index1, matcher in enumerate(matchers):
#Loop through each value in full_name and store (index, value)
for index2, name in enumerate(full_name):
#Check if matcher is a substring of name
if(matcher in name):
#If true then add indices to the list
matches.append([index1, index2])
這是一個更短、更 Pythonic 的版本:
matches = [[i1, i2] for i1 in range(len(matchers)) for i2 in range(len(full_name)) if matchers[i2] in full_name[i1]]
Output 兩者:[[0, 0], [0, 3], [3, 4], [4, 2]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.