[英]How to compare items among 3 lists
I am trying to add comparison among 3 lists.我正在尝试添加 3 个列表之间的比较。 listB is compared to listA and then listA is compared to listC to create a new combined items.
listB 与 listA 进行比较,然后 listA 与 listC 进行比较以创建新的组合项。
listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
listC = ['abcd755 - staff1', 'abcd754 - staff2', '3xas34a - demo1', '01shdsa - staff3', '23xas34a - demo2']
out = []
for b in listB:
if any((c := a).startswith(b) for a in listA):
out.append(c)
print(out)
Current Output: # comparing 2 list当前 Output:#比较 2 列表
['abcd754 - (32.12)', 'abcd755 - (45)', '01shdsa - (0.01)']
Output Needed: # a combination of data from amonglists Output 需要:#来自列表的数据组合
['abcd754 - (32.12) - staff2', 'abcd755 - (45) - staff1', '01shdsa - (0.01) - staff3']
Your listA and listC are effectively key-value pairs, so you could convert them to dictionaries and then look up their values for the entries in listB:您的 listA 和 listC 是有效的键值对,因此您可以将它们转换为字典,然后在 listB 中查找它们的条目的值:
dict_a = dict(n.split(" - ", maxsplit=1) for n in listA)
dict_c = dict(n.split(" - ", maxsplit=1) for n in listC)
for b in listB:
if b in dict_a and b in dict_c:
out.append(f"{b} - {dict_a[b]} - {dict_c[b]}")
>>> out
['abcd754 - (32.12) - staff2',
'abcd755 - (45) - staff1',
'01shdsa - (0.01) - staff3']
Edit: If you want everything where listA and listB have matching keys and don't actually need listB (Which acts as a filter here), you can bypass listB altogether:编辑:如果你想要 listA 和 listB 具有匹配键并且实际上不需要 listB (这里充当过滤器)的所有内容,你可以完全绕过 listB :
for key in set(dict_a).intersection(dict_c):
out.append(f"{key} - {dict_a[key]} - {dict_c[key]}")
>>> out
['3xas34a - (43.23) - demo1', # notice that this will then also be catched
'abcd754 - (32.12) - staff2',
'01shdsa - (0.01) - staff3',
'abcd755 - (45) - staff1']
Also notice that with this approach, the order of elements might be different, though you can get around that if really needed.另请注意,使用这种方法时,元素的顺序可能会有所不同,但如果确实需要,您可以解决这个问题。
# your code goes here
listA = ['abcd755 - (45)', 'abcd754 - (32.12)', '3xas34a - (43.23)', '01shdsa - (0.01)']
listB = ['abcd754', '23xas34a', 'abcd755', '01shdsa']
listC = ['abcd755 - staff1', 'abcd754 - staff2', '3xas34a - demo1', '01shdsa - staff3', '23xas34a - demo2']
from collections import defaultdict as dd
out = dd(list)
for i in listA:
a, b = i.split(' - ')
out[a].append(b)
for i in listC:
a, b = i.split(' - ')
if a in out:
out[a].append(b)
result = []
for i in listB:
if i in out:
result.append(' - '.join([i, *out[i]]))
print(result)
['abcd754 - (32.12) - staff2', 'abcd755 - (45) - staff1', '01shdsa - (0.01) - staff3']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.