【问题标题】:Python, trying to generate dictionary inside comprehensive listPython,试图在综合列表中生成字典
【发布时间】:2015-02-25 11:27:14
【问题描述】:

如果我想使用内部理解和三元从单词列表生成字典,我会遇到一些问题并需要帮助。

应该在没有额外模块导入的情况下生成字典,使用单词长度作为键,单词作为值。 这是我最简化的问题:

l=['hdd', 'fdd', 'monitor', 'mouse', 'motherboard']

d={}

for w in l :
    if len(w) in d  : d[ len(w) ].append( w )
    else            : d[ len(w) ] = [ w ]

# and dictionary inside list is OK:
print [d]
>>>[{11: ['motherboard'], 3: ['hdd', 'fdd'], 5: ['mouse'], 7: ['monitor']}]

然后尝试使其全面:

d={}
print [ d[ len(w) ].append( w ) if len(w) in d else d.setdefault( len(w), [w] ) for w in l ]
>>>[['hdd', 'fdd'], None, ['monitor'], ['mouse'], ['motherboard']]

...这不起作用。有什么帮助吗?

【问题讨论】:

  • 这是因为您的列表将包含您的表达式的返回值。在提示符中尝试print d[3].append(123) 看看。实际字典d 很好。
  • 点赞让我看看。

标签: python dictionary list-comprehension dictionary-comprehension


【解决方案1】:

一切都很好,但你没有看到正确的东西:不要打印列表理解返回的内容。
它通过列表理解为您提供d[ len(w) ].append( w ) 产量的列表,但您感兴趣的只是d

l=['hdd', 'fdd', 'monitor', 'mouse', 'motherboard']

d={}
[ d[ len(w) ].append( w ) if len(w) in d else d.setdefault( len(w), [w] ) for w in l ]
print d
>>> {11: ['motherboard'], 3: ['hdd', 'fdd'], 5: ['mouse'], 7: ['monitor']}

这似乎是您所期望的。

【讨论】:

  • 嘿!在这种情况下,理解只是语法:)
猜你喜欢
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 2021-01-23
  • 2019-05-09
相关资源
最近更新 更多