[英]Converting a list or string into a dictionary and returning only specific keys/values from that dictionary
[英]Function returning a dictionary with string lengths (keys) and number of occurrence (values) from a list
我正在尝试编写一个 function ,它接受一个字符串列表并返回一个字典,其中键表示长度,值表示列表中有多少字符串具有该长度。 这是我写的和我的output:
def length_counts(stringList):
stringDict = {}
for value in stringList:
stringDict[len(value)] = stringList.count(value)
return stringDict
#test
sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"]
print(length_counts(sa_countries))
Output:
{6: 1, 9: 1, 7: 1, 4: 1}
正确的 output 应该是:
{6: 1, 9: 2, 7: 2, 4: 1}
表示有 1 个 6 个字母的字符串、2 个 9 个字母的字符串、2 个 7 个字母的字符串和 1 个 4 个字母的字符串。
count 将为您提供该特定元素的出现次数。 所以委内瑞拉的计数会给你列表中委内瑞拉的数量,而不是 9 个字母单词的数量。 尝试这样的事情。
sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"]
dict = {}
for country in sa_countries:
if (len(country) in dict):
dict[len(country)] += 1
else:
dict[len(country)] = 1
print(dict)
您可以使用collections.defaultdict
来累积字符串长度计数。
from collections import defaultdict
def length_counts(countries):
result = defaultdict(int)
for country in countries:
result[len(country)] += 1
return result
例子
>>> length_counts(sa_countries)
defaultdict(<class 'int'>, {6: 1, 9: 2, 7: 2, 4: 1})
你正在重写你的价值观。
首先,您执行stringList.count('Venezuela')
,即 1。然后执行stringList.count('Argentina')
,这也是 1。因此,他们的键9
两次获得值1
。
我要做的是首先将初始列表转换为包含长度的列表。
sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"]
sa_countries_lens = [len(s) for s in sa_countries]
即[6, 9, 9, 7, 7, 4]
。 现在我要数一数:
from collections import Counter
Counter(sa_countries_lens)
结果是
Counter({6: 1, 9: 2, 7: 2, 4: 1})
Counter 基本上是一个 dict,你可以用一个增量和一个键检查来做一个 dict,但是 Counter 更好,它是标准库的一部分并且非常普遍。
一种可能的方法是使用collections.Counter ; 计数是Counter
的用途:
from collections import Counter
sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"]
result = Counter(map(len, sa_countries))
print(result)
Output
Counter({9: 2, 7: 2, 6: 1, 4: 1})
从文档中:
Counter 是用于计算可散列对象的 dict 子类。 它是一个集合,其中元素存储为字典键,它们的计数存储为字典值。 计数可以是任何 integer 值,包括零计数或负计数。 计数器 class 类似于其他语言中的 bag 或 multisets。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.