Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典副本_Python_List_Dictionary - Fatal编程技术网

Python字典副本

Python字典副本,python,list,dictionary,Python,List,Dictionary,我有两张单子 list_a = [1, 1, 2, 2, 4, 5] list_b = ['good', 'bad', 'worst', 'cheap', 'waste', 'waste1'] 我试图在list\u a中编写python脚本和映射元素,元素在list\u b中,如果有人输入值1,所有相关值都应该填充。例如,如果我输入1作为输入参数,则输出应为 good bad worst cheap 如果我输入2作为输入参数,则输出应为 good bad worst cheap 我尝试

我有两张单子

list_a = [1, 1, 2, 2, 4, 5]
list_b = ['good', 'bad', 'worst', 'cheap', 'waste', 'waste1']
我试图在
list\u a
中编写python脚本和映射元素,元素在
list\u b
中,如果有人输入值
1
,所有相关值都应该填充。例如,如果我输入
1
作为输入参数,则输出应为

good
bad
worst
cheap
如果我输入
2
作为输入参数,则输出应为

good
bad
worst
cheap
我尝试了python字典,但字典不允许重复键。有没有办法在Python中实现这一点?

这是一个罕见的用例:

compress
获取一个iterable值和一个iterable“truthy或falsy”值,当第二个iterable提供truthy成对值时,从第一个iterable返回项。因此,在本例中,当
list\u a
中的值与提供的索引匹配时,我们需要
list\u b
中的项,我们使用生成器表达式动态计算该索引

请注意,对于重复查找,
dict
是更好的选择。简单地使用:

lookup = {1: ['good', 'bad'], 2: ['worst', 'cheap'], 4: ['waste'], 5: ['waste1']}

将允许您在查找[idx]时有效地执行x的
:根据需要打印(x)
(可能捕获
keyrerror
以忽略密钥不存在时的情况,或生成更友好的错误消息)。

您只需从两个列表中创建字典即可。可能会节省一些打字时间

list_a = [1, 1, 2, 2, 4, 5]
list_b = ['good', 'bad', 'worst', 'cheap', 'waste', 'waste1']

d = {}
for x, y in zip(list_a, list_b):
  if d.get(x):
    d[x] += [y]
  else:
    d[x] = [y]

print(d[2])

提示:您的字典值可以是列表。字典可以包含像
{1:['good','bad'],4:['waste']}
这样的列表。有什么方法可以做到这一点吗?他简直就是给你打的。为什么很少见呢?@swimingduck:因为它只对一次流式传输海量数据有用(输入太大,无法一次保存在内存中);对于多个过程和/或小数据,您只需查找我在编辑中添加的表单。@ShadowRanger感谢您的解决方案。您能告诉我如何从上面生成查找={1:['good','bad'],2:['best','cheap'],4:['waste'],5:['waste1']}吗lists@sudhir:
result=collections.defaultdict(list)
用于zip中的k,v(list\u a,list\u b):结果[k]。追加(v)
result=dict(result)
(最后一位是可选的,转换回普通的
dict
,不会自动激活丢失的键)。太棒了。这就是我要找的。我太笨了,我一直用tuple(zip(list_a,list_b))代替dict