python中的列表/dict理解以更新字典,并用字符串中的键和值
有人知道如何将以下循环转换为一行中的列表或字典理解吗? 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查找带有设置的唯一键,然后计数。注意
set
不保留(键)插入顺序!Find unique keys with set and then count. Note the
set
doesn't not keep (keys) insertion order!使用计数器会做。节省您的时间为字符串进行循环。如果您需要使用字典类型,则可以稍后将其转换为字典。
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.