python中的列表/dict理解以更新字典,并用字符串中的键和值

发布于 2025-01-29 08:15:27 字数 260 浏览 3 评论 0原文

有人知道如何将以下循环转换为一行中的列表或字典理解吗? type(inter)=字符串,type(stringOne)=字符串,type(dictresult)= dictionary。 ,'c':1,'d':3}谢谢!!!

stringOne = 'abcddd'
dictResult = {}
for letter in stringOne:
    dictResult[letter] = dictResult.get(letter,0) + 1

Does anyone know how to convert below for loop into a list or dictionary comprehension in one line? type(letter) = string,type(stringOne) = string,type(dictResult) = dictionary.For example, stringOne = 'abcddd', I want the output to be dictResult = {'a': 1, 'b': 1, 'c': 1, 'd': 3} Thanks!!!

stringOne = 'abcddd'
dictResult = {}
for letter in stringOne:
    dictResult[letter] = dictResult.get(letter,0) + 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

川水往事 2025-02-05 08:15:27

查找带有设置的唯一键,然后计数。注意set不保留(键)插入顺序!

stringOne = 'abcddd'

dictResult = {char: stringOne.count(char) for char in set(stringOne)}

print(dictResult)

Find unique keys with set and then count. Note the set doesn't not keep (keys) insertion order!

stringOne = 'abcddd'

dictResult = {char: stringOne.count(char) for char in set(stringOne)}

print(dictResult)
郁金香雨 2025-02-05 08:15:27

使用计数器会做。节省您的时间为字符串进行循环。如果您需要使用字典类型,则可以稍后将其转换为字典。

from collections import Counter
counter = Counter(stringOne)
dict(counter)

Make use of Counter will do. Save you the time to do a loop for the string. Can just convert to dictionary later if you required it to be in dictionary type.

from collections import Counter
counter = Counter(stringOne)
dict(counter)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文