List/Dict Python 中的理解以使用字符串中的键和值更新字典
List/Dict comprehension in Python to update a dictionary with keys and values from a string
有谁知道如何在一行中将下面的 for 循环转换为列表或字典理解? type(letter) = string,type(stringOne) = string,type(dictResult) = dictionary.For 例如,stringOne = 'abcddd',我希望输出为 dictResult = {'a': 1 , 'b': 1, 'c': 1, 'd': 3} 谢谢!!!
stringOne = 'abcddd'
dictResult = {}
for letter in stringOne:
dictResult[letter] = dictResult.get(letter,0) + 1
利用计数器就可以了。节省您为字符串做循环的时间。如果您需要它是字典类型,可以稍后转换为字典。
from collections import Counter
counter = Counter(stringOne)
dict(counter)
使用集合查找唯一键,然后计数。请注意 set
不会保留(键)插入顺序!
stringOne = 'abcddd'
dictResult = {char: stringOne.count(char) for char in set(stringOne)}
print(dictResult)
有谁知道如何在一行中将下面的 for 循环转换为列表或字典理解? type(letter) = string,type(stringOne) = string,type(dictResult) = dictionary.For 例如,stringOne = 'abcddd',我希望输出为 dictResult = {'a': 1 , 'b': 1, 'c': 1, 'd': 3} 谢谢!!!
stringOne = 'abcddd'
dictResult = {}
for letter in stringOne:
dictResult[letter] = dictResult.get(letter,0) + 1
利用计数器就可以了。节省您为字符串做循环的时间。如果您需要它是字典类型,可以稍后转换为字典。
from collections import Counter
counter = Counter(stringOne)
dict(counter)
使用集合查找唯一键,然后计数。请注意 set
不会保留(键)插入顺序!
stringOne = 'abcddd'
dictResult = {char: stringOne.count(char) for char in set(stringOne)}
print(dictResult)