【问题标题】:List comprehesion using a dictionary使用字典进行列表理解
【发布时间】:2015-05-12 20:01:13
【问题描述】:

我有这本词典:

 primes = {2: True, 3: True, 4: False, 5: True, 6: False, 7: True} 

我想创建一个列表,其中只有一对为真。它看起来像这样:

[2, 3, 5, 7]

所以我尝试这样做:

primelist = [x for x, y in primes if y]

但我得到了错误:

TypeError: 'int' object is not iterable

我做错了什么?

【问题讨论】:

    标签: python list dictionary list-comprehension


    【解决方案1】:

    你已经接近了!你只需要在字典上调用.items() method1

    primelist = [x for x, y in primes.items() if y]
    

    在 Python 中迭代字典只会产生它的键,而不是某些人可能期望的键和值。要获得这些,您调用 .items() 以返回一个可迭代的键/值对,然后可以将其解压缩为名称 xy


    1请注意,这个答案是关于 Python 3.x 的。在 Python 2.x 中,您应该调用 .iteritems(),因为 Python 2.x 的 .items() 方法会构建一个不必要的列表。

    【讨论】:

    • 我在 Python 3.x 中做这件事。这是一个愚蠢的错误。谢谢!
    【解决方案2】:
    >>> filter(primes.get, primes)
    [2, 3, 5, 7]
    

    (这是 Python 2,对于 Python 3,您需要在其周围加上 list(...)。)

    我现在用高达一百万的数字对其进行了速度测试。 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]
    


    参考资料:filter()list()items()

    【讨论】:

    • 哇...当我将其添加到我的时,您使用 filter 回答了!但是,嘿,你的更好,因为它没有lambda ...应该想到的!
    • filter(primes.get, primes) 可能会更好。您很少需要直接访问特殊方法。但仍然很酷的答案。 :)
    • @BhargavRao 请注意 iCodez 指出的改进。而且我只是对它进行了速度测试,在 Python 2 上它实际上比列表理解。我没想到。
    • 非常酷的答案。我刚刚开始学习 Python,它的表现力给我留下了深刻的印象!
    • 是的!我意识到我的答案现在是错误的 enuf :'( ...将删除它,因为它是多余的!
    【解决方案3】:

    如果valueTrue,您可以遍历items,并存储key

    >>> [k for k,v in primes.items() if v]
    [2, 3, 5, 7]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2021-03-05
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      相关资源
      最近更新 更多