【问题标题】:Why aren't key value pairs produced when a list comprehension is used?为什么在使用列表推导时不生成键值对?
【发布时间】:2016-11-09 20:51:01
【问题描述】:

我有一本字典,我正在尝试使用列表理解对键值对使用条件来过滤字典。代码没有抛出错误,但输出格式错误。 for 循环有效,但列表推导无效。为什么?我更喜欢使用列表推导。

news1 = {'check':1,'this':2, 'thing':3, 'out':4, 'dude':5 }
news2 = {'just':1,'for':2, 'antother':3, 'chance':4, 'now':5 }

for item in x:
    if x[item] > 2:
        print item

def list1(x):
    print  ((item, x[item]) for item in x if x[item] > 2)

【问题讨论】:

  • 您没有在代码中的任何位置定义x
  • 应该是print [(item, x[item]) for item in x if x[item] > 2]。在() 括号中,您正在创建生成器而不是列表理解
  • 如果你不提及你得到什么输出,你想要什么,你就不会在这里得到正确的答案。因为我们无法读懂你的想法。另外,提一下x的内容
  • 成功了,谢谢!!
  • @AbhishekDesai 底部有 2 个答案相同的解决方案,请务必将其中一个标记为答案!

标签: python dictionary conditional list-comprehension keyvaluepair


【解决方案1】:

圆括号表示不同的生成器理解。使用方括号:

print  [(item, x[item]) for item in x if x[item] > 2]

【讨论】:

    【解决方案2】:

    print [(item, x[item]) for item in x if x[item] > 2]

    会起作用,因为 () 用于其他东西,x 也应该被定义为一些东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 2019-09-13
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多