【问题标题】:How would I sort a list from a CSV file in ascending order?如何按升序对 CSV 文件中的列表进行排序?
【发布时间】:2016-04-01 18:35:05
【问题描述】:
with open('classroom1.csv') as csvfile:
    readCSV = csv.reader(csvfile)
    for row in readCSV:
        name = row[0]
        scores = [int(c) for c in row[1:]]
        total = sum(scores)

到目前为止,这是我的代码,我想按升序对其进行排序。我知道reverse=True 会帮助我,但我不知道如何在这里使用它。

我试过了:

srt = sorted(total, key=lambda x : x[1], reverse=True)
    print(name,srt)

但它不起作用。

我的列表是[userName, score1, score2, score3],例如[James, 5, 8, 4]

【问题讨论】:

  • 如果我们知道您的列表是什么样的以及应该是什么样的,那将会很有帮助。
  • 所以你想要['James',5,4,8] --> ['James',4,5,8]?
  • @Stidgeon 按总分排序。
  • 如果没有MCVE,这是没有希望的
  • 请不要破坏您的问题。如果您想删除您的问题,请标记以引起版主注意。

标签: python sorting csv


【解决方案1】:

如果你需要升序排序,你不应该调用reverse=True

如果:classroom1.csv

Ali,100,100
Bob,50,100

而 main.py 是:

data=[]
with open('classroom1.csv') as csvfile:
    readCSV = csv.reader(csvfile)
    for row in readCSV:
        name = row[0]
        scores = [int(c) for c in row[1:]]
        total=sum(scores)
        data.append((name,total))
srt=sorted(data, key=lambda x : x[1])
print srt

您将收到:

[('Bob',150),('Ali',200)]

【讨论】:

    【解决方案2】:
    Program to short by userName with high score:
    Here  is my cvs file data:
    
    userName, score1,score2,score3
    James, 7,3,8
    Bob, 9,5,7
    Yogi, 10,4,5
    
    import csv
    output = {}
    first = True
    f=open("D:\work\classroom1.cvs")
    for row in csv.reader(f):
        if first:
            first = False
            continue
        key = row[0]
        row.pop(0)
        val = list(set(map(int, row)))[0]
        output[key] = val
    
    for key in sorted(output):
        print ("%s, %s" % (key, output[key]))
    
    
    Output:
    >>> ================================ RESTART ================================
    >>> 
    Bob, 9
    James, 8
    Yogi, 10
    

    >>>

    Program to short by high score:
    Here  is my cvs file data:
    
    userName, score1,score2,score3
    James, 7,3,8
    Bob, 9,5,7
    Yogi, 10,4,5
    Abhi, 1,2,3
    
    import csv
    import operator
    output = {}
    first = True
    f=open("D:\work\classroom1.cvs")
    for row in csv.reader(f):
        if first:
            first = False
            continue
        key = row[0]
        row.pop(0)
        val = list(set(map(int, row)))[0]
        output[key] = val
    
    sorted_output = sorted(output.items(), key=operator.itemgetter(1))
    for key,val in sorted_output:
        print ("%s, %s" % (key, val))
    
    
    Output:
    >>> ================================ RESTART ================================
    >>> 
    Abhi, 1
    Bob, 9
    Yogi, 9
    James, 10
    >>> 
    

    【讨论】:

    • 我试过这段代码,但没有任何输出。我将一行代码更改为 f=open('classroom1.cvs',"a+") 因为我一直收到错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2018-05-03
    • 2019-07-23
    • 2021-09-04
    相关资源
    最近更新 更多