Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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_List Comprehension - Fatal编程技术网

Python 使用字典列出压缩

Python 使用字典列出压缩,python,list,dictionary,list-comprehension,Python,List,Dictionary,List Comprehension,我有这本字典: primes = {2: True, 3: True, 4: False, 5: True, 6: False, 7: True} primelist = [x for x, y in primes.items() if y] 我想创建一个列表,其中只有一对是真的。它看起来是这样的: [2, 3, 5, 7] 所以我试着这样做: primelist = [x for x, y in primes if y] 但我得到了一个错误: TypeError: 'int' ob

我有这本字典:

 primes = {2: True, 3: True, 4: False, 5: True, 6: False, 7: True} 
primelist = [x for x, y in primes.items() if y]
我想创建一个列表,其中只有一对是真的。它看起来是这样的:

[2, 3, 5, 7]
所以我试着这样做:

primelist = [x for x, y in primes if y]
但我得到了一个错误:

TypeError: 'int' object is not iterable

我做错了什么

你接近了!您只需调用字典上的1:

 primes = {2: True, 3: True, 4: False, 5: True, 6: False, 7: True} 
primelist = [x for x, y in primes.items() if y]
在Python中迭代字典只会产生它的键,而不是一些人所期望的键和值。要获得这些值,您可以调用
.items()
返回一个键/值对的iterable,然后将其解压为名称
x
y



1请注意,这个答案与Python3.x有关。在Python2.x中,您应该调用
.iteritems()
,因为Python2.x
.items()
方法将构建一个不必要的列表。

如果
为True

>>> [k for k,v in primes.items() if v]
[2, 3, 5, 7]
(这是Python2,对于Python3,您需要在其周围添加一个
列表(…)

我现在用高达一百万的数字对它进行了速度测试。平均100次跑步:

Python 2.7.9:
0.0908 seconds for filter(primes.get, primes)
0.2372 seconds for [n for n, p in primes.items() if p]

Python 3.4.3:
0.1856 seconds for list(filter(primes.get, primes))
0.0953 seconds for [n for n, p in primes.items() if p]


引用:

我正在用Python3.x做这件事。这是一个愚蠢的错误。非常感谢。哇!当我将其添加到我的时,您使用了
过滤器
!但是,嘿,你的更好,因为它没有
lambda
。。。我早该想到的<代码>过滤器(primes.get,primes)
可能会更好。您很少需要直接访问特殊方法。不过答案还是很酷的@巴尔加夫罗注意到iCodez指出的改进。我刚刚对它进行了测试,在Python2上,它实际上比列表理解快。我没想到,回答很酷。我刚刚开始学习Python,它的表现力给我留下了深刻的印象!是 啊我现在意识到我的答案是错误的:“(…将删除它,因为它是多余的!