[英]How do I check if combination of elements of two lists exists in a third list?
我有一個看起來像這樣的元組列表
data = [("hyd", "ab", 10.99), ("del", "ab", 12.99), ("del", "cc", 10.19), ("cal", "dd", 4.99), ("hyd", "ee", 13.11), ("noi", "dd", 10.49), ("noi", "bb", 10.99),]
我在下面還有另外兩個列表
loc = ["noi", "del", "cal", "hyd"]
dealer = ["ee", "dd", "ab", "cc", "bb"]
現在,對於dealer
每個元素,我想要一個loc
每個對應元素的值列表
因此,由於dealer
有5個元素,因此我將為loc
每個對應元素提供5個帶有值的列表。
就像是
對於ee
,它將再次檢查loc
列表的每個元素,並從數據中找出loc
每個元素包含的值
對於ee
[None, None, None, 13.11]
因此我們可以看到ee
上面檢查了noi
,在分配給None的values
什么都沒有找到,然后它檢查了del
,沒有找到分配了None的東西,然后它對cal
進行了檢查,發現了什么,分配了None,但對於hyd
卻找到了13.11並因此分配了價值。
同樣的,
對於dd
[10.49, None, 4.99, None]
,依此類推...
如何獲得針對經銷商五個要素的五個清單?
我試圖做這樣的事情
temp_list = []
for i in dealer:
print("i", i)
for j in loc:
print("j", j)
for k in data:
#print("k", k)
if i in k and j in k:
temp_list.append(k[2])
else:
temp_list.append(None)
但是我沒有得到預期的輸出。 我如何獲得清單?
完成預期的輸出
ee [None, None, None, 13.11]
dd [10.49, None, 4.99, None]
ab [None, 12.99, None, 10.99]
cc [None, 10.99, None, None]
bb [10.99, None, None, None]
您可以以更高效的方式進行操作。 您的解決方案是O(len(data)* len(dealers)* len(locations))。 我們可以在O(len(data))中通過僅對數據進行一次迭代來完成:
data = [("hyd", "ab", 10.99), ("del", "ab", 12.99), ("del", "cc", 10.19), ("cal", "dd", 4.99), ("hyd", "ee", 13.11), ("noi", "dd", 10.49), ("noi", "bb", 10.99),]
locations = ["noi", "del", "cal", "hyd"]
dealers = ["ee", "dd", "ab", "cc", "bb"]
out = {dealer: [None] * len(loc) for dealer in dealers}
loc_index = {val: index for index, val in enumerate(locations)}
for location, dealer, amount in data:
try:
out[dealer][loc_index[location]] = amount
except (IndexError, KeyError):
pass
print(out)
# {'ee': [None, None, None, 13.11], 'cc': [None, 10.19, None, None],
# 'dd': [10.49, None, 4.99, None], 'ab': [None, 12.99, None, 10.99],
# 'bb': [10.99, None, None, None]}
使用更好的數據結構!
假設data
兩個元素在前兩個元素中不能相等,那么可以使用以下字典來簡化生活:
>>> from collections import defaultdict
>>>
>>> data = [("hyd", "ab", 10.99), ("del", "ab", 12.99), ("del", "cc", 10.19), ("cal", "dd", 4.99), ("hyd", "ee", 13.11), ("noi", "dd", 10.49), ("noi", "bb", 10.99),]
>>> d = defaultdict(dict)
>>>
>>> for key, subkey, val in data:
...: d[key][subkey] = val
...:
>>> d
>>>
defaultdict(dict,
{'cal': {'dd': 4.99},
'del': {'ab': 12.99, 'cc': 10.19},
'hyd': {'ab': 10.99, 'ee': 13.11},
'noi': {'bb': 10.99, 'dd': 10.49}})
...因為現在您可以執行以下操作:
>>> loc = ["noi", "del", "cal", "hyd"]
>>> dealer = ["ee", "dd", "ab", "cc", "bb"]
>>>
>>> [[d[lo].get(deal) for lo in loc] for deal in dealer]
>>>
[[None, None, None, 13.11],
[10.49, None, 4.99, None],
[None, 12.99, None, 10.99],
[None, 10.19, None, None],
[10.99, None, None, None]]
...或者如果您想要一個dict
:
>>> {deal:[d[lo].get(deal) for lo in loc] for deal in dealer}
>>>
{'ab': [None, 12.99, None, 10.99],
'bb': [10.99, None, None, None],
'cc': [None, 10.19, None, None],
'dd': [10.49, None, 4.99, None],
'ee': [None, None, None, 13.11]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.