我有一个看起来像这样的元组列表
public function tickets()
{
return $this->hasMany(Tickets::class);
}
我在下面还有另外两个列表
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
中有5个元素,因此我将列出五个列表,其中包含dealer
中每个对应元素的值。
类似
对于loc
,它将再次检查ee
列表中的每个元素,并从数据中找出它对loc
的每个元素包含什么值
对于loc
ee
因此我们可以看到以上[None, None, None, 13.11]
对ee
的检查,在noi
中没有找到任何东西,因此没有分配。然后,它对values
进行了检查,没有找到任何东西因此没有分配,然后它针对del
进行检查,什么也没找到,没有分配任何值,但是对于cal
,它找到了13.11,因此分配了值。
类似地,
对于hyd
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)
答案 0 :(得分:2)
您可以以更有效的方式进行操作。您的解决方案是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]}
答案 1 :(得分:2)
使用更好的数据结构!
假设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]}