简体   繁体   English

我如何使用所有数字而不是python中的第一位对列表进行排序?

[英]how do i sort the list using all digits not just first digit in python?

sorted(users, key=attrgetter('user_id'), reverse=True)[:10] 已排序(用户,键= attrgetter('user_id'),反向= True)[:10]

This line is sorting the list of object based on first digit but i want all digit to consider during sort in python. 这行基于第一位数对对象列表进行排序,但是我希望所有位数在python排序期间都要考虑。

#!/usr/bin/python

import sys
from operator import attrgetter

class User:
    def __init__(self, x, y):
        self.name = x
        self.user_id = y

    def __repr__(self):
        return self.name + ":" + str(self.user_id)


users = []

for line in sys.stdin:
    data = line.strip().split('\t')
    users.append(User(data[0],data[-1]))


for user in users:
    print(user)

print('-----------')

for user in sorted(users, key=attrgetter('user_id'), reverse=True)[:10]:
    print(user)

Convert the strings to int and sorting them would help you sort using all the digits. 将字符串转换为int并对其进行排序将帮助您使用所有数字进行排序。

for line in sys.stdin:
    data = line.strip().split('\t')
    users.append(User(data[0],int(data[-1])))

If user_id is an integer, you should treat it as such by casting it to int. 如果user_id是整数,则应将其强制转换为int来进行处理。 This will make the sort work as expected. 这将使排序工作按预期进行。 Make one of these changes: 进行以下更改之一:

class User:
    def __init__(self, x, y):
        self.name = x
        self.user_id = int(y)

    def __repr__(self):
        return self.name + ":" + str(self.user_id)

or, alternatively, 或者,

users = []

for line in sys.stdin:
    data = line.strip().split('\t')
    users.append(User(data[0],int(data[-1])))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用列表中每个项目中的数字对列表进行排序? Python - How to sort a list using digits in each item of the list? Python 如何根据最后两位数字对数字列表进行排序? - How do I sort a list of numbers based on the last two digits? 如何使用 tesseract 而不是仅第一个数字来读取完整的数字序列 - How can I read a full sequence of digits using tesseract instead of first digit only python如何按digit = string排序字符串列表 - python How to sort list of string by digit=string 如何将一串数字变成一个一位整数列表? - How do I turn a string of digits into a list of one-digit integers? 在python中,如何将一位数转换为两位数字符串? - in python how do I convert a single digit number into a double digits string? 如何将列表中的两位数字拆分为个位数? - How do to split the 2 digit numbers in a list into single digits? 如何将Python列表中的后续数字连接成双(或更多)数字 - How to join subsequent digits in a Python list into a double (or more) digit number 如何在 Python 中创建每个 3 位数字组合的列表? - How do I create a list of every combination of 3 digit numbers in Python? 我将如何制作一个没有重复数字且第一位必须为 0 的 4 位数字? - How would I make a 4-digit number with no repeating digits and the first digit has to be 0?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM