如何从两个列表创建字典而不丢失重复值?

2022-01-17 00:00:00 python list dictionary set

问题描述

我有两个列表:

pin_list = ['in0', 'in1', 'in2', 'y']
delvt_list = ['0.399', '0.1995', '0.1995', '0.399']

我使用以下代码:temp = dict(zip(delvt_list,pin_list)) 但我得到以下信息:

I use the code: temp = dict(zip(delvt_list,pin_list)) but I get the following:

temp = {'0.1995': 'in2', '0.399': 'y'}

我需要编写哪些 Python 代码才能获得:

What Python code do I need to write to get:

temp =  {'0.1995': {'in2', 'in1'}, '0.399': {'y', 'in0'}}

temp =  {'0.1995': ['in2', 'in1'], '0.399': ['y', 'in0']}

作为一个附加问题,如果我想使用 temp 中的值来搜索我正在阅读的行,使用集合或列表会更容易吗?

As an additional question, if I want to use the values in temp to search a line that I am reading in would it be easier with sets or lists?


解决方案

使用 collections.defaultdict:

temp = defaultdict(set)

for delvt, pin in zip(delvt_list, pin_list):
    temp[delvt].add(pin)

这会创建一个 defaultdict,其中默认值是一个集合,然后循环并添加每个键的值.

This creates a defaultdict where the default value is a set, then loop and add the values for each key.

如果您想要一个列表,只需更改默认类型以及添加值的方式以匹配 list 接口:

If you wanted a list instead, simply change the default type and how you add values to match the list interface:

temp = defaultdict(list)

for delvt, pin in zip(delvt_list, pin_list):
    temp[delvt].append(pin)

当您想要测试成员资格时,集合是一个更好的主意(something in aset);这样的测试需要恒定的时间,而不是列表的线性时间(因此集合成员资格测试需要固定的时间,与集合的大小无关,而对于列表,它需要更多的时间,与列表中的元素数量成正比).

Sets are a better idea when you want to test for membership (something in aset); such tests take constant time, vs. linear time for a list (so set membership tests take a fixed amount of time independent of the size of the set, while for lists it takes more time, proportional to the number of elements in the list).

相关文章