gpt4 book ai didi

python - 是否有更节省时间的有效方法来填充字典

转载 作者:太空宇宙 更新时间:2023-11-04 03:25:56 25 4
gpt4 key购买 nike

我有两个整数列表 A 和 B,长度相同。列表 A 是一个无序列表整数,而列表 B 是一个有序(按升序)整数列表。

A 和 B 的创建使得成对的 A[i]、B[i] 对不相同。

我的目标是创建一个字典,其中键值取自 A,值取自 B,与 A[i] 成对匹配,即,

myDict = {}

for i in A:
myDict[i] = []

for i in range(len(A)):
targetA = A[i]
targetB = B[i]
if targetA in myDict.keys():
myDict[targetA].append(targetB)

对于非常大的数据集,这会花费很长时间。是否有另一种方法可以最终得出相同的字典,可能是通过利用 B 的排序结构?

最佳答案

您可以使用 defaultdict这应该更简单和更快:

from collections import defaultdict

A = [6, 6, 3, 2, 5, 2, 3]
B = [1, 2, 3, 3, 4, 6, 7]

purchase_dict = defaultdict(list)
for key, value in zip(A, B):
purchase_dict[key].append(value)

来自docs :

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault().

你得到了什么:

>>> purchase_dict
defaultdict(<class 'list'>, {2: [3, 6], 3: [3, 7], 5: [4], 6: [1, 2]})
>>> purchase_dict[2]
[3, 6]

关于python - 是否有更节省时间的有效方法来填充字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33004718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com