gpt4 book ai didi

python - 将字符串的字符频率重写为理解

转载 作者:行者123 更新时间:2023-11-28 21:34:38 25 4
gpt4 key购买 nike

以下过程代码片段计算文本字符串的字符频率并写入字典。字典以字符作为键,频率作为值。

text = "asampletextstring"
char_count = {}
for char in text:
if char_count.get(char):
char_count[char] += 1
else:
char_count[char] = 1

我的问题是,是否可以将上面的代码片段重写为理解

最佳答案

这是可能的,但是效率低下:

text = "asampletextstring"

char_count = { char : text.count(char) for char in text }

print(char_count)

输出

{'s': 2, 'x': 1, 'p': 1, 'm': 1, 'e': 2, 'r': 1, 'n': 1, 'g': 1, 'a': 2, 'i': 1, 'l': 1, 't': 3}

您可以编写更短的代码:

char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1

关于python - 将字符串的字符频率重写为理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090152/

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