gpt4 book ai didi

Python,尝试在综合列表中生成字典

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:15 25 4
gpt4 key购买 nike

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

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

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']]

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

最佳答案

一切都很好,但你没有看到正确的东西:不要打印列表理解返回的内容。
它为您提供 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']}

这似乎正是您所期望的。

关于Python,尝试在综合列表中生成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28717836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com