如果嵌套列表中的第n个元素相同,则为Python求和(列表列表)

时间:2018-04-07 04:48:24

标签: python python-3.x list

如果第n个元素在嵌套列表(列表列表)中相同,则为Python总和

my_list1=[['John',2,'goals',4],['Robert',5,'hike',3],['Julia',6,'paid',2],['John',4,'fine',6],['Robert',3,'loop',44],['Julia',1,'cool',33],['Kris',6,'wild',4],['Kris',8,'word',67]]

结果

my_list1=[['John',2,'goals',4],['Robert',5,'hike',3],['Julia',6,'paid',2],['John',4,'fine',6],['Robert',3,'loop',44],['Julia',1,'cool',33],['Kris',6,'wild',4],['Kris',8,'word',67]]
result = {}
for i in my_list1:
    name = i[0]
    if name in result:
        result[name][1] += i[1]
        result[name][2] += i[3]
    else:
        result[name] = [name, i[1], i[3]]
my_list2=[]
[my_list2.extend([v]) for k,v in result.items()]
print (my_list2)

import pandas as pd
x =[['John',2,'goals',4],['Robert',5,'hike',3],['Julia',6,'paid',2],['John',4,'fine',6],['Robert',3,'loop',44],['Julia',1,'cool',33],['Kris',6,'wild',4],['Kris',8,'word',67]]
df = pd.DataFrame(x)
xx = (df.groupby(0).sum().reset_index().as_matrix())
s=[]
for i in xx:
    for j in i:
        s.append(j)
new = []
for i in range(0, len(s), 3):
    new.append(s[i:i+3])
print(new)

由于

1 个答案:

答案 0 :(得分:0)

创建一个字典,其中键是名称,值是总和列表。

CAST