首页 > 解决方案 > comparing elements of a list of list and removing

问题描述

l=[['a', 'random_str', 4], ['b', 'random_str2', 5], ['b', 'random_str3', 7]]

so I have a list like this and I want to traverse through this list to check if the zeroth index of each sublist is equivalent to one another so check if any zeroth index of each sublist is equal to another, and then if two of or more are similar check the second index in the sublist and only keep the sublist with lowest int value and remove all others.

so the output should be that

[['a', 'random_str', 4], ['b', 'random_str2', 5]]

so it removes the sublist with the higher int in the second index

I'm thinking something like this

for i in l:
    for k in i:
        if k[0]=i[0][0]:
            # then I dont know 

标签: pythonpython-3.x

解决方案


It can be achieved with pandas, a sort_values and a groupby:

import pandas as pd
l=[['a', 'random_str', 4], ['b', 'random_str2', 5], ['b', 'random_str3', 7]]

#create dataframe from list of list
df = pd.DataFrame(l)

#sort column based on third column / index = 2
df = df.sort_values(by=2)

#groupby first column and only take first entry which is lowest int after sort.
df = df.groupby(0).head(1)

#put back to list of list
df = df.values.tolist()

print(df)

prints out

[['a', 'random_str', 4], ['b', 'random_str2', 5]]

推荐阅读