我确信这是可以做到的,但到目前为止我还没有成功:
我有一个字符串列表。我想创建一个字典,其中所述字符串的长度(可以表示为一个范围)作为键,字符串本身作为值。
例子: 这是我的列表:['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/