【问题标题】:How to sort an array of records into descending order如何将记录数组按降序排序
【发布时间】:2021-11-14 19:10:50
【问题描述】:

我有一个名为 sample.csv 的 csv 文件,我已将它转换为一条记录,这条记录设置有一个字符串值和一个整数值,如下所示:

[Name,10]
[Name1,12]
[Name2,14]

我希望能够将这些记录按降序排序,然后最终打印三个得分最高的学生的姓名和分数以及得分最低的学生的姓名和分数。这是我到目前为止的代码,我我无法按整数值对记录进行排序。

import csv
file = open("sample.csv")
csvreader = csv.reader(file)
rows = []
for row in csvreader:
    rows.append(row)
file.close()

sortedFile=[]

sortedFile=sorted(rows, key=lambda rows: rows[1])

print(sortedFile)

编辑:

一个非常有帮助的人发表了评论,但现在他们删除了他们的评论。

import csv
file = open("sample.csv")
csvreader = csv.reader(file)
rows = []
for row in csvreader:
    rows.append(row)
file.close()

sortedFile=[]

sortedFile=sorted(rows, key=lambda rows: int(rows[1]))[::-1]

print(sortedFile[0])
print(sortedFile[1])
print(sortedFile[2])
print(sortedFile[-1])

我的代码现在看起来像这样,我快完成了,我相信我错过了一些非常简单的东西,我想要的只是数组附近的一些文本说

"The person with the highest score is", (name[0]),"with a score of,(score[0])
"The person with the highest score is", (name[1]),"with a score of,(score[1])
"The person with the highest score is", (name[2]),"with a score of,(score[2])
"The person with the lowest score is", (name[-1]),"with a score of,(score[-1])

【问题讨论】:

  • sortedFile=sorted(rows, key=lambda rows: int(rows[1]))?

标签: python arrays sorting record


【解决方案1】:

可能是这样的:

 sortedFile = sorted(rows, key=lambda rows: int(rows[1]))? 

【讨论】:

    【解决方案2】:

    假设您的数据在一个列表中,您可以调用 sortkey 参数来指定如何对列表进行排序。在这种情况下,您可以使用负值-x[1] 对其进行倒序排序。

    data = [['Name',10],
    ['Name1',12],
    ['Name2',14]]
    
    data.sort(key = lambda x: -x[1])
    

    结果:

    [['Name2', 14], ['Name1', 12], ['Name', 10]]
    

    【讨论】:

      【解决方案3】:

      我建议进行以下更改:

      import csv
      
      with open("sample.csv", 'r') as file:
          csvreader = csv.reader(file)
          sortedFile = sorted(csvreader, key=lambda rows: int(rows[1]), reverse=True)
      
      print(sortedFile)
      
      for (i,place) in zip([0,1,2,-1], ['highest', '2nd highest', '3rd highest', 'lowest']):
          print('The person with the {} score is {} with a score of {}.'.format(place, sortedFile[i][0], sortedFile[i][1]))
      

      示例输入sample.csv

      Alice,12
      Max,11
      Medhi,18
      Chen,17
      Sasha,15
      

      示例输出

      [['Medhi', '18'], ['Chen', '17'], ['Sasha', '15'], ['Alice', '12'], ['Max', '11']]
      The person with the highest score is Medhi with a score of 18.
      The person with the 2nd highest score is Chen with a score of 17.
      The person with the 3rd highest score is Sasha with a score of 15.
      The person with the lowest score is Max with a score of 11.
      

      【讨论】:

        【解决方案4】:

        您按升序对代码进行排序,并根据条件按降序排列。

        试试这个选项:

        代码:

        rows=[['A',10],
        ['B',12],
        ['C',11]]
        
        sortedFile=sorted(rows, key=lambda rows: int(rows[1]))[::-1]
        
        if len(sortedFile) > 1:    
            print(sortedFile)
            for i in range(len(sortedFile) - 1):
                print(sortedFile[i])
            print(sortedFile[-1])
        elif len(sortedFile) == 1:
            print(sortedFile)
            print(sortedFile[0])
        else:
            print('list is empty')
        

        此代码考虑了 3 个条件。如果列表长度大于1,则等于1,等于0。


        为了漂亮的输出,你可以使用 f-strings,例如,像这样:

        print(f'The person with the highest score is {name[0]}, with a score of {score[0]}')
        

        我会用我自己的例子来告诉你:

        if len(sortedFile) > 1:
            for i in range(len(sortedFile) - 1):
                print(f'The person with the highest score is {sortedFile[i][0]}, with a score of {sortedFile[i][1]}')
            print(f'The person with the highest score is {sortedFile[-1][0]}, with a score of {sortedFile[-1][1]}')
        elif len(sortedFile) == 1:
            print(f'The person with the highest score is {sortedFile[0][0]}, with a score of {sortedFile[0][1]}')
        else:
            print('list is empty')
        

        【讨论】:

        • 这是完美的伙伴,我想早点回复,但我认为可能有问题,我想知道是否有办法也有一些文本,所以我可以说 (name0) (score[0])、(name[1]) 的分数与 (score[1) 等的分数?
        • 您可以对sorted 使用reverse=True 可选关键字参数,而不是使用[::-1] 反转列表
        • @mhannah04 有可能,我已经回答完毕了。
        • @Stef 你说得对,我就是这么决定的)
        • @Tehnorobot 这太棒了,tyvm!
        猜你喜欢
        • 1970-01-01
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多