python - 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
解决方案
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]]
推荐阅读
- r - 如何使用 R 编辑 html 文件中的代码
- split - Camel RoutingSlip 需要在 Split 中使用 end()
- python - 如何在顶级窗口python上创建垂直和水平滚动条
- python - 使超级方法的 PyCharm 自动完成参数
- ios - 使用 ARKit 2 检测对象时显示边界框
- android - 如何从反应原生应用程序生成独立签名的 APK,与分离的博览会?
- apache-spark - 最大模式长度 fpGrowth (Apache) PySpark
- sql - 如何在oracle 12c中找到前12个月连续四个月的平均值
- ios - 如何在 UILongPressGestureRecognizer iOS Swift 4 中传递多个参数?
- sql - 从oracle中的多行表中检索行