【问题标题】:Order CSV with two digit numbers使用两位数字订购 CSV
【发布时间】:2020-08-12 14:01:08
【问题描述】:

我正在尝试为游戏创建一个排行榜,在玩完游戏后,python 脚本会访问一个 CSV 文件(未排序)并打印出得分最高的前 5 名人员。 Python 似乎对一位数的数字做得很好,但我无法让它与两位数一起工作。代码如下:

import csv
import operator

sample = open('csv_sample2.txt', 'r')

csv1 = csv.reader(sample,delimiter=',')

sort = sorted(sample, key=operator.itemgetter(1))

for eachline in sort:
    print(eachline)

这是输出: (我现在只是使用占位符名称)

['Matt Damon', ' 12']
['Robin Williams', ' 14']
['Billy Crystal', ' 15']
['Minnie Driver', ' 17']
['Peter Sellers', ' 6']
['Robert De Niro', ' 8']
['Stanley Kubrick', ' 9']

这是原始排行榜文件:

Matt Damon, 12
Robert De Niro, 8
Billy Crystal, 15
Peter Sellers, 6
Stanley Kubrick, 9
Robin Williams, 14
Minnie Driver, 17

我怎样才能正确排序数字?

【问题讨论】:

  • 为什么要对文件进行排序,还要将其读取为CSV?,使用lambda x : int(x[1])之类的关键函数
  • 您必须将字符串转换为整数值才能获得合适的排序。
  • csv1 已定义,但在撰写本文时未使用。故意的?

标签: python csv sorting


【解决方案1】:

我建议简单地使用 file.readlines() 读取文件,然后处理完成的结果。

输入文件:

Matt Damon, 12
Robert De Niro, 8
Billy Crystal, 15
Peter Sellers, 6
Stanley Kubrick, 9
Robin Williams, 14
Minnie Driver, 17

代码:

data = []
with open('your_file.txt', 'r') as f:
    scores = f.readlines()
    # data is a list of tuples with a string name as the 
    # first value and a integer score as the second value
    data = [ ( s.strip().split(', ')[0], int(s.strip().split(', ')[1]) ) for s in scores ]

sorted_data = sorted(data, key=lambda tup: tup[1], reverse=True)

for name, score in sorted_data:
    print(f'{name} got a score of {score}')

# Prints:
# Minnie Driver got a score of 17
# Billy Crystal got a score of 15
# Robin Williams got a score of 14
# Matt Damon got a score of 12
# Stanley Kubrick got a score of 9
# Robert De Niro got a score of 8
# Peter Sellers got a score of 6

要仅打印有序列表 sorted_data 中的前五个分数,请使用 for x in range() 循环:

for x in range(5):
    name, score = sorted_data[x]
    print(f'{name} got a score of {score}')

这个 for 循环将运行 5 次。它解压缩存储在sorted_data x 的元组中包含的名称和分数,然后打印出该数据。

【讨论】:

  • 这个有效,谢谢!你知道我将如何更改代码以仅打印前 5 名吗?
  • 不客气。我更新了我的答案,以显示如何仅打印前 5 名。
  • 谢谢你,这是一个huuuuuge的帮助,你是一个救生员
【解决方案2】:

您的数据可能不会被识别为数字?

data = [['Matt Damon', ' 12'],
        ['Robin Williams', ' 14'],
        ['Billy Crystal', ' 15'],
        ['Minnie Driver', ' 17'],
        ['Peter Sellers', ' 6'],
        ['Robert De Niro', ' 8'],
        ['Stanley Kubrick', ' 9']]
# conversion to floats
data = [[item[0], float(item[1])] for item in data]

sorted(data, key=lambda x: x[1])

给我:

[['Peter Sellers', 6.0],
 ['Robert De Niro', 8.0],
 ['Stanley Kubrick', 9.0],
 ['Matt Damon', 12.0],
 ['Robin Williams', 14.0],
 ['Billy Crystal', 15.0],
 ['Minnie Driver', 17.0]]

【讨论】:

    【解决方案3】:
     ...: sample = [['Matt Damon', ' 12'],
        ...: ['Robin Williams', ' 14'],
        ...: ['Billy Crystal', ' 15'],
        ...: ['Minnie Driver', ' 17'],
        ...: ['Peter Sellers', ' 6'],
        ...: ['Robert De Niro', ' 8'],
        ...: ['Stanley Kubrick', ' 9']]
        ...:
        ...: def get_int_item(o):
        ...:     return  int(o[1])
        ...:
        ...:
        ...: sort = sorted(sample, key=get_int_item)
        ...:
        ...: for eachline in sort:
        ...:     print(eachline)
        ...:
    ['Peter Sellers', ' 6']
    ['Robert De Niro', ' 8']
    ['Stanley Kubrick', ' 9']
    ['Matt Damon', ' 12']
    ['Robin Williams', ' 14']
    ['Billy Crystal', ' 15']
    ['Minnie Driver', ' 17']
    

    【讨论】:

    • 你可以使用@riov8 建议的 tha lambda 函数
    【解决方案4】:

    您的号码中的答案是通过字符串而不是整数来识别的。 尝试使用int()转换分数,但注意不要输入operator.itemgetter对象。 int() 函数只接受字符串、类似字节的对象或数字。

    sample = open('csv_sample2.txt', 'r')
    csv1 = csv.reader(sample,delimiter=',')
    sort = sorted(csv1, key=lambda k: int(k[1]))
    

    如果您不想要空间,只需使用 str.strip() 摆脱它们。

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多