【问题标题】:Sorting Alphabetically and Numerically按字母和数字排序
【发布时间】:2016-03-07 23:55:24
【问题描述】:
f = open(document) #this will open the selected class data
swag = [f.readline(),f.readline(),f.readline(),f.readline(),f.readline(),f.readline()] #need to make go on for amount of line

viewfile = input("Do you wish to view the results?")#This will determine whether or not the user wishes to view the results
if viewfile == 'yes': #If the users input equals yes, the program will continue
order = input("What order do you wish to view to answers? (Alphabetical)") #This will determine whether or not to order the results in alphabetical order
if order == 'Alphabetical' or 'alphabetical':
    print(sorted(swag))
if order == 'Top' or 'top':
    print(sorted(swag, key=int))

文件读作

John : 1
Ben : 2
Josh : 3

我将如何将它们按数字顺序排列,例如降序?

【问题讨论】:

  • if x == y or z 不会像您认为的那样做。另外,如果文件有不同的行数怎么办?另外,int("John : 1") 的结果是什么?
  • 那么我该如何解决这个问题?
  • [f.readline(),f.readline(),..] 是一种将文件读入数组的糟糕方法。使用循环,卢克,使用循环!
  • 您的代码有多个问题。我建议看看official Python tutorial
  • @tobias_k 使用现有的 API,Luke 将是下一课... :)

标签: python sorting numerical alphanumeric


【解决方案1】:

您必须按数值排序,然后无论得到什么结果,只需将其反转即可反转顺序。

这里的关键是通过为 sorted 的 key 参数定义一个函数来按您需要做的正确事情进行排序。

这里的函数是一个lambda,它简单地返回要排序的字符串的数字部分;它将按升序返回。

要颠倒顺序,只需颠倒列表即可。

with open(document) as d:
   swag = [line.strip() for line in d if line.strip()]

by_number = sorted(swag, key=lambda x: int(x.split(':')[1]))
descending = by_number[::-1]

【讨论】:

  • 你可以使用sorted(..., reverse=True)
  • 或许也很有趣的说法是:by_name = sorted(swag, key=lambda x: x.split(':')[0])
【解决方案2】:

您需要在: 处拆分每一行。从名称中删除空格并将数字转换为整数(如果有的话,也可以是浮点数)。跳过空行。

with open(document) as fobj:
    swag = []
    for line in fobj:
        if not line.strip():
            continue
        name, number_string = line.split(':')
        swag.append((name.strip(), int(number_string)))

排序很简单:

by_name = sorted(swag)
by_number = sorted(swag, key=lambda x: x[1])
by_number_descending = sorted(swag, key=lambda x: x[1], reverse=True)

变化

使用itemgetter

from operator import itemgetter

by_number_descending = sorted(swag, key=itemgetter(1), reverse=True)

【讨论】:

  • 如果文件中有空行会中断。
  • @BurhanKhalid 修复了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
相关资源
最近更新 更多