python - 使用我的代码在 python 中将字符串转换为字典

标签 python string dictionary

我有一个字符串l1例如包含以下内容:aackcdldccc 。我想使用字典计算每个字符出现的次数。所需的最终结果应该是这样的字典:

a:2
c:5
k:1
d:2
l:1

如何修复我的代码以使其正常工作? 我使用以下代码并收到错误消息:

l1= ('aackcdldccc')
print (l1)
d={}
print (len(l1))
for i in (range (len(l1))): 
        print (i)
        print (l1[i])
        print (list(d.keys()))
        if l1[i] in list(d.keys()):
            print ('Y')
            print (l1[i])
            print (list(d.keys())[l1[i]])
            d1 = {l1[i]:list(d.values())[l1[i]+1]}
            #print (d1)
            #d.update (d1)
        else:
            print ('N')
            d1={l1[i]:1}
            d.update (d1)

这是我得到的错误: aackcdldccc

11
0
a
[]
N
1
a
['a']
Y
a

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-185-edf313da1f8d> in <module>()
     10             print ('Y')
     11             print (l1[i])
---> 12             print (list(d.keys())[l1[i]])
     13             #d1 = {l1[i]:list(d.values())[l1[i]+1]}
     14             #print (d1)

TypeError: list indices must be integers or slices, not str

最佳答案

有两种方法可以做到这一点:

In [94]: s = 'aackcdldccc'

In [95]: collections.Counter(s)
Out[95]: Counter({'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1})

In [96]: d = {}

In [97]: for char in s:
    ...:     d.setdefault(char, 0)
    ...:     d[char] += 1
    ...: 

In [98]: d
Out[98]: {'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1}

关于python - 使用我的代码在 python 中将字符串转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101899/

相关文章:

c - 在C中创建字符串矩阵

Java字符串分割正则表达式返回带有多个分隔符的空字符串

python - 从嵌套字典中获取父键

python - Python中区分 'character'和 'numeric'数据类型

python - 不使用科学记数法将 numpy 数组保存为 CSV

python - 是否可以在 python 中求解带有单位的符号?

Python 复数零虚部格式化

java - 为什么 Guava 的 MultiMap 的 size 方法返回(非)预期的结果?

python - Python 字典的顺序是否在迭代中得到保证?

python - 写入然后读取内存字节 (BytesIO) 给出空白结果