首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >python 实现复合字段排序,如 :身高一样比体重,如何实现呢?

python 实现复合字段排序,如 :身高一样比体重,如何实现呢?

作者头像
流川疯
发布于 2022-05-10 19:59:36
发布于 2022-05-10 19:59:36
6880
举报

文章大纲


假设有一个题目:

现在学校排队 按照身高升序排列,身高相同按照体重降序(升序)排列,身高体重都相同,按照原有先后顺序排列

样例输入:

代码语言:javascript
复制
shengao = [150,150,160,160,170]
tizhong = [100,100,100,105,100]

输出:(体重升序)

代码语言:javascript
复制
index = [1,2,3,4,5]

纯算法思路

代码语言:javascript
复制
if __name__ == '__main__':
    index = range(0,len(shengao))
    liebiao = zip(index,shengao,tizhong)
    bmi = list(liebiao)
    bmi.sort(key=lambda x: (x[1], x[2]))

    print(bmi)

输出

代码语言:javascript
复制
[(0, 150, 100), (1, 150, 100), (2, 160, 100), (3, 160, 105), (4, 170, 100)]

这样的思路有一个问题,无法实现,复核字段排序的负责逻辑


面向对象思路

java ,c++ 都有Compare接口, 主要就是实现比较的接口

比如c++ 类似代码:

代码语言:javascript
复制
//对人的年龄进行升序排列,年龄相同对身高进行降序排列,年龄身高相同对体重升序排列
#include <iostream>
#include <list>
#include <string>

using namespace std;


class Person
{
public:
	Person( string Name, int Age,int Heigh,int weight)
	{
		this->m_Name = Name;
		this->m_Age = Age;
		this->m_Heigh = Heigh;
		this->m_weight = weight;
	}
	string m_Name;
	int m_Age;
	int m_Heigh;
	int m_weight;
};

bool Compare(Person& p1, Person& p2)
{
	if (p1.m_Age == p2.m_Age)
	{
		if (p1.m_Heigh == p2.m_Heigh)
		{
			return p1.m_weight < p2.m_weight;
		}
		else
		{
			return p1.m_Heigh > p2.m_Heigh;
		}
	}
	else
	{
		return p1.m_Age < p2.m_Age;
	}
}
void test01()
{
	list<Person> l;
	Person p1 = { "张飞", 23, 170 ,74};
	Person p2 = { "关羽", 23, 170 ,80};
	Person p3 = { "赵云", 23, 180 ,78};
	Person p4 = { "刘备", 25, 199 ,90};
	
	l.push_back(p1);
	l.push_back(p2);
	l.push_back(p3);
	l.push_back(p4);

	cout << "-----------------------" << endl;
	for (list<Person>::iterator i = l.begin(); i != l.end(); i++)
	{
		cout << "姓名:" << i->m_Name << " " << "年龄:" << i->m_Age << " " << "身高:" << i->m_Heigh 
			<< "体重:" << i->m_weight <<endl;
	}
	cout << "-----------------------" << endl;
	l.sort(Compare);
	for (list<Person>::iterator i = l.begin(); i != l.end(); i++)
	{
		cout << "姓名:" << i->m_Name << " " << "年龄:" << i->m_Age << " " << "身高:" << i->m_Heigh 
		<< "体重:" << i->m_weight << endl;
	}
}
int main()
{
	test01();
	return 0;
}

参考文献

https://www.runoob.com/python3/python3-att-list-sort.html

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-04,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 文章大纲
  • 纯算法思路
  • 面向对象思路
  • 参考文献
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档