我有两个整数列表 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_factoryfunction which returns an empty list. Thelist.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 thelist.append()operation adds another value to the list. This technique is simpler and faster than an equivalent technique usingdict.setdefault().
你得到了什么:
>>> purchase_dict
defaultdict(<class 'list'>, {2: [3, 6], 3: [3, 7], 5: [4], 6: [1, 2]})
>>> purchase_dict[2]
[3, 6]
