按列快速排序列表 [英] Quicksort a list of list by column

查看:54
本文介绍了按列快速排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我通过熊猫从 csv 生成的列表进行快速排序.我想按特定列对其进行排序,例如数字或高度.

i would like to quicksort a list of list which i generatet from a csv via pandas. I want to sort it by a specific column e.g. number oder height.

数据如下所示:

<头>
数字姓名高度宽度重量
1仇恨66.2357.28124.87
2Bamity22.56843.7123.67
3阿育王45.66234.3523.29

我已经能够使用此代码按第二列对其进行排序:

I was already able to sort it by the second column with this code:

def quickSort(list):
  if not list:
      return list
  pivot = list[0]
  lesser = quickSort([x for x in list[1:] if x[1] < pivot[1]])
  greater = quickSort([x for x in list[1:] if x[1] >= pivot[1]])
  return lesser + [pivot] + greater
print(quickSort(product_list))

这适用于按名称排序.但我不知道要更改什么才能按任何其他列排序.如果有人能帮助我就好了.

This is working fine for sorting by name. But i dont know what to change to sort by any other column. It would be great if somebody could help me.

推荐答案

product_list = [[1,10],[3,8],[2,9]]

def quickSort(list, compare_fn):
  if not list:
      return list
  pivot = list[0]
  lesser = quickSort([x for x in list[1:] if compare_fn(x, pivot)], compare_fn)
  greater = quickSort([x for x in list[1:] if not compare_fn(x, pivot)], compare_fn)
  return lesser + [pivot] + greater
print(quickSort(product_list, lambda x,y: x[0] < y[0]))

这篇关于按列快速排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆