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

标签 python list dictionary

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

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

例子: 这是我的列表:['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/

相关文章:

Python:如何在两个单独的数组之间找到两个相等/最接近的值?

python - 使用 s3fs 下载文件

list - 如何将列表转换为 Erlang 中的函数参数?

python - 将多个值列表映射到 python 字典中的键列表?

python - 如何增加脚本运行时迭代的数组数量?

python - 如何多次循环访问相同的列表?

c++ - 错误 : passing ‘const std::map<int, int>’ as ‘this’ argument discards qualifiers [-fpermissive]

python - 根据其值的类型处理字典,并使用字典理解生成另一个字典

java - 我已经为 SortedMap 创建了一个 put() 方法,但似乎无法让测试代码正常工作

python - np.inf 和 float ('Inf' 之间的区别)