[英]How to find matching partial items from two list
再會。
我有以下 2 個列表,我需要比較它們才能匹配。 我需要查找 listB 項目是否在 listA 中,然后返回 listA 中的項目。
listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
out = []
for b in listB:
if any(a.startswith(b) for a in listA):
out.append(b)
print (out)
當前Output:
['abcd754', 'abcd755', '01shdsa']
意向 Output:
['abcd754 - (32.12)', 'abcd755 - (45)' , '01shdsa - (0.01)']
您可以使用賦值運算符:=
:
listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
out = []
for b in listB:
if any((c := a).startswith(b) for a in listA):
out.append(c)
print(out)
印刷:
['abcd754 - (32.12)', 'abcd755 - (45)', '01shdsa - (0.01)']
您只需要遍歷 listA 而不是 listB。
listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
out = []
for a in listA:
if any(a.startswith(b) for b in listB):
out.append(a)
print (out)
#['abcd755 - (45)', 'abcd754 - (32.12)', '01shdsa - (0.01)']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.