gpt4 book ai didi

python使用字符串列表创建字典,字符串长度作为值

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:24 28 4
gpt4 key购买 nike

我确信这是可以做到的,但到目前为止我还没有成功:

我有一个字符串列表。我想创建一个字典,其中所述字符串的长度(可以表示为一个范围)作为键,字符串本身作为值。

例子:这是我的列表:['foo','bar','help','this','guy']

我想以这样的字典结尾:{3:['foo','bar','guy], 4:['this','help']}

最佳答案

使用 defaultdict 这样您就不必检查是否为新 key 创建列表:

from collections import defaultdict

x = ['foo','bar','help','this','guy']

len_dict = defaultdict(list)

for word in x:
len_dict[len(word)].append(word)

len_dict
#
# Out[5]: defaultdict(list, {3: ['foo', 'bar', 'guy'], 4: ['help', 'this']})

关于python使用字符串列表创建字典,字符串长度作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824080/

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