如何从两个列表创建字典而又不丢失重复值? [英] How to create dictionary from two lists without losing duplicate values?

查看:108
本文介绍了如何从两个列表创建字典而又不丢失重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

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).

这篇关于如何从两个列表创建字典而又不丢失重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆