查找列表元素的平均值,如果使用 Python 满足条件?



我有一个具有以下格式的列表:

mylist = ["Joe, 100%", "Joe, 80%", "Joe, 90%", "Sally, 95%", "Sally, 80%", "Jimmy, 90%", ...]

我想做的是,首先计算每个名字出现的次数。如果名称出现 2 次或更多次,请将该名称与平均百分比一起附加。因此,我正在尝试获得以下输出:

newlist = ["Joe, 90%", "Sally, 87.5%"]

为了尝试这个,我mylist.split(", ")只获取名称,并使用Counter()来查找名称出现的次数。然后,我使用一个简单的if >= 2语句将名称附加到newlist,如果名称出现 2 次或更多次。

然而,尽管尝试了许多不同的事情,但我无法弄清楚如何用最终列表中的名字恢复百分比。我也不确定如何在谷歌上表达我的问题,所以我无法找到任何帮助。有谁知道如何做到这一点?如果这个问题是重复的,请告诉我(并提供一个链接以便我学习(,我可以删除这个问题。谢谢!

你可以试试这个:

from collections import defaultdict
counts = defaultdict(int)
percents = defaultdict(int)
for item in mylist:
name, percent = item.split(',')
percent = int(percent.lstrip().rstrip('%'))
percents[name]+=percent
counts[name]+=1
result = []
for k,v in counts.items():
if v > 1:
result.append(f"{k}, {percents[k]/v}%")
print(result)

输出

['Joe, 90.0%', 'Sally, 87.5%']

我建议您创建一个分数字典,其中键是名称,值将是其分数列表。此代码段显示了如何实现此目的:

mydict = {}
for item in mylist:
name, score = item.split(", ") # splits each item into a score and a name
score = float(score.replace("%", "")) # converts string score to a float
if mydict[name]: # checks if the name already exists in the dictionary
mydict[name].append(score)
else:
mydict[name] = [score]

这将为您留下一本按名称组织的分数字典。现在您所要做的就是平均字典中的分数:

newlist = []
for name in mydict:
if len(mydict[name]) >= 2:
average = str(sum(mydict[name]))/len(mydict[name])) + "%"
straverage = name + ", " + average
newlist.append(straverage)

最新更新