英文:
How to average values in list of lists that contain same parameter
问题
我想要对包含相同第一个值的所有列表中的第二个值进行平均,并将这些平均列表转换为一个新的列表。
例如,我想要将这个列表转换成这样:
[['foo', 平均(13+15)],
['bar', 平均(14+16+5)]]
有没有简单的方法来做到这一点?
英文:
I want to average the 2nd values in all lists that contain the same 1st value, and convert these averaged lists into a new list of lists.
For example i want to convert this:
[['foo', 13],
['foo', 15],
['bar', 14],
['bar', 16],
['bar', 5]]
to this:
[['foo', avg(13+15)],
['bar', avg(14+16+5)]]
Any ideas of a simple way to do this?
答案1
得分: 1
from itertools import groupby
from statistics import mean # 3 or greater
# if using 2.7
def mean(x): return sum(x)/len(x)
a = [['foo', 13],
['foo', 15],
['bar', 14],
['bar', 16],
['bar', 5]]
[[key, mean(map(lambda x: x[1], list(group)))] for key, group in groupby(a, lambda x: x[0])]
# [['foo', 14], ['bar', 11]]
英文:
from itertools import groupby
from statistics import mean # 3 or greater
# if using 2.7
def mean(x): return sum(x)/len(x)
a = [['foo', 13],
['foo', 15],
['bar', 14],
['bar', 16],
['bar', 5]]
[[key, mean(map(lambda x: x[1], list(group)))] for key, group in groupby(a, lambda x:x[0])]
# [['foo', 14], ['bar', 11]]
Groups the list on the first element then computes the mean. Assumes you have a mean function.
答案2
得分: 0
这应该可以工作。您可以很容易地使用字典来解决这个问题。虽然可能有更好的方法,但这是其中一种方法。
l = [['foo', 13], ['foo', 15], ['bar', 14], ['bar', 16], ['bar', 5]]
dictionary = {}
for i in range(0, len(l)):
if l[i][0] in dictionary:
dictionary[l[i][0]].append(l[i][1])
else:
dictionary[l[i][0]] = [l[i][1]]
# 上面的字典基本上将所有属于一个键的元素存储在一个列表中,可以通过引用键来获取它。
l = []
for keys in dictionary:
l.append([keys, sum(dictionary[keys]) / len(dictionary[keys])]) # 如果您想要作为输出的二维列表
dictionary[keys] = sum(dictionary[keys]) / len(dictionary[keys])
print(dictionary) # 打印 { 'foo': 14.0, 'bar': 11.666.. }
print(l) # 打印 [['foo', 14.0], ['bar', 11.666666666666666]],顺序不保持。
英文:
This should work. You could have easily used dictionary for this problem. Though there might be better approaches, this is one of the approach.
l=[['foo', 13], ['foo', 15], ['bar', 14], ['bar', 16], ['bar', 5]]
dictionary={}
for i in range(0,len(l)):
if l[i][0] in dict:
dictionary[l[i][0]].append(l[i][1])
else:
dictionary[l[i][0]]=[l[i][1]]
# The above dictionary basically stores all the elements belonging to a key in a list which we can get by referring the key.
l=[]
for keys in dict:
l.append([keys,sum(dictionary[keys])/len(dictionary[keys])]) #If you want 2d list as the output
dictionary[keys]=sum(dictionary[keys])/len(dictionary[keys])
print(dictionary) # Prints {'foo': 14.0, 'bar': 11.666..}
print(l) # Prints [['foo', 14.0], ['bar', 11.666666666666666]] and order isn't maintained.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论