如何使用python将具有重复值的两个列表合并到字典中

2lpgd968  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(446)

考虑
a=[1,2,2,4,4,5,6]b=[1,2,3,4,4,5,6]
我想要一个如下的输出:(1,1)(2,2)(2,3)(4,4)(4,4)(5,5)(6,6)
使用zip将删除a中的重复值。有人能告诉我怎么做吗?

jq6vz3qz

jq6vz3qz1#

这将为您提供一个元组列表,因此您将保留“重复项”:

a = [1,2,2,4,4,5,6]
b = [1,2,3,4,4,5,6]
output = list(zip(a,b))

输出:

[(1, 1), (2, 2), (2, 3), (4, 4), (4, 4), (5, 5), (6, 6)]

但如果你这样做了:

output = dict(zip(a,b))

你会得到:

{1: 1, 2: 3, 4: 4, 5: 5, 6: 6}

那是因为 dict 结构不能有重复的键。此数据结构用于将唯一键Map到值(https://docs.python.org/3/tutorial/datastructures.html#dictionaries).
所以,你不可能得到这样的东西:

{1:1, 2:2, 2:3, 4:4, 4:4, 5:5, 6:6}

但是你有一个解决办法:你可以使用 defaultdict 其中每个密钥都与 list 或者 set ,例如:

from collections import defaultdict

a = [1,2,2,4,4,5,6]
b = [1,2,3,4,4,5,6]

# We create a defaultdict with a list as its default_factory

# (see link below for the documentation)

list_of_tuples = list(zip(a,b))

output = defaultdict(list)

# Here we wil create the "key: value" pairs of the defaultdict

# For each tuple in the list,

# use the first item to create the unique key if needed

# and append the second item to the value (which is a list)

for k,v in list_of_tuples:
    output[k].append(v)

print(output)

输出:

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

有关defaultdict的文档:https://docs.python.org/3/library/collections.html#collections.defaultdict

pgky5nke

pgky5nke2#

我可以给你一份清单:

a,b  = [1,2,2,4,4,5,6] ,[1,2,3,4,4,5,6]

ab = list(zip(a,b))

print(ab)

输出:

[(1, 1), (2, 2), (2, 3), (4, 4), (4, 4), (5, 5), (6, 6)]

相关问题