如何制作一个新的功能收集结果?

时间:2018-10-05 05:10:53

标签: python list

 t = [{"a" :11, "r_gr" :1, "gn":"F", "e" :18},
      {"a" :13, "r_gr" :3, "gn":"M", "e" :19},
      {"a" :1, "r_gr" :3, "gn":"M", "e" :29},
      {"a" :0, "r_gr" :2, "gn":"F", "e" :18},
      {"a" :0, "r_gr" :2, "gn":"M", "e" :18},
      {"a" :3, "r_gr" :1, "gn":"F", "e" :25}]
  1. 我想创建一个新列表:s = [a的总和],类似于r_gr的[14,0,14]顺序                      和r = [“ r_gr”]像[1,2,3]                      和e = [“ e”的第一个数字],例如[1,1,2,1,1,2]

2 个答案:

答案 0 :(得分:2)

或使用itertools(内置软件包)和一些列表推导(我建议采用这种方式):

import itertools
t.sort(key=lambda x: x['r_gr'])
a = [sum(int(item['a']) for item in group) for key, group in itertools.groupby(t, key=lambda x: x['r_gr'])]
r_gr = sorted(set([i['r_gr'] for i in t]),key=[i['r_gr'] for i in t].index)
e = [int(str(i)[0]) for i in [x['e'] for x in t]]
print(a)
print(r_gr)
print(e)

输出:

[14, 0, 14]
[1, 2, 3]
[1, 2, 1, 1, 1, 2]

答案 1 :(得分:0)

我会使用pandas库,因为如果将它们放在表中,看起来很容易解决:

import pandas as pd
df = pd.DataFrame(t)
s = df.groupby("r_gr").sum().tolist()
r = df["r_gr"].sort_values().drop_duplicates().tolist()
e = df["e"].astype(str).str.slice(0, 1).astype(int).tolist()