如何在python嵌套列表中对数据进行分类

时间:2019-05-24 17:05:52

标签: python list

我需要对python嵌套列表进行如下分类。

[
['amal', 20],
['kamal', 25],
['amal', 30]
]

答案应该是

[amal,20,30]
[kamal,25]

3 个答案:

答案 0 :(得分:1)

您可以使用itertools.groupby根据第一个值对子列表进行分组:

from itertools import groupby
from operator import itemgetter as g

[[k, *(i[1] for i in v)] for k,v in groupby(sorted(l, key=g(0)), g(0))]
# [['amal', 20, 30], ['kamal', 25]]

答案 1 :(得分:1)

另一种方法可以在Pandas DataFrame上对groupby起作用:

import pandas as pd

data = [
    ['amal', 20],
    ['kamal', 25],
    ['amal', 30]
]

df = pd.DataFrame(data, columns=['key', 'value'])
grouped = data.groupby('key').agg(list)
print(grouped.head())

答案 2 :(得分:0)

这是实现此目标的另一种方法。

list1 = [
['amal', 20],
['kamal', 25],
['amal', 30]
]

ls2=[]
k = set([i[0] for i in list1])
for i in k: 
    k2 = [ j[1] for j in list1 if j[0]==i]
    k2.insert(0,i)
    ls2.append(k2)

ls2
# Output: [['kamal', 25], ['amal', 20, 30]]