栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python结构体与结构体排序

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python结构体与结构体排序

一、模仿C语言的结构体读入数据
class student: # 固定格式
    def __init__(self): # 固定格式
        self.name = ""
        self.num = ""
        self.age = ""


list1 = [] # 创建空列表来准备存储
for i in range(0, 3):
    list1.append(student()) #每次循环增加一个结构体元素
    list1[i].name, list1[i].num, list1[i].age = input().split() # 读入,按空格分开
    list1[i].age = int(list1[i].age) # 将读入的str类型转为int类型
# 至此实现将结构体读入列表数组
二、结构体自定义排序cmp实现
n = int(input()) # 读入n


class student: # 固定格式
    def __init__(self): # 固定格式
        self.name = ""
        self.num = ""
        self.sco = 0


from functools import cmp_to_key # 引入模块


def cmp(a, b): # 定义cmp
    if a.sco < b.sco: # 无需像C语言一样定义a与b的类型,直接用
        return -1 # 不调换
    else:
        return 1 # 调换


list1 = [] # 创建空列表
for i in range(0, n):
    list1.append(student())
    list1[i].name, list1[i].num, list1[i].sco = input().split()
    list1[i].sco = int(list1[i].sco)
list1.sort(key=cmp_to_key(cmp)) # 按照cmp来排序

print(list1[0].name, list1[0].num, list1[0].sco) # 输出特定元素
三、结构体自定义排序lambda实现
n = int(input()) # 读入n


class student: # 固定格式
    def __init__(self): # 固定格式
        self.name = ""
        self.num = ""
        self.sco = 0


list1 = [] # 创建空列表
for i in range(0, n):
    list1.append(student())
    list1[i].name, list1[i].num, list1[i].sco = input().split()
    list1[i].sco = int(list1[i].sco)
list1.sort(key=lambda x: x.sco) # 按照结构体x的sco项来排序,同样不需要像C语言一样定义x的类型

print(list1[0].name, list1[0].num, list1[0].sco) # 输出特定元素
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/283526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号