【问题标题】:Sorted Lists not working properly in python排序列表在python中无法正常工作
【发布时间】:2019-05-31 02:48:00
【问题描述】:

我正在对一个包含 14 个标题和 500,000 条记录的 csv 文件进行排序。我使用 enumerate 函数组织了它们。但是,当我使用 sorted() 函数使用键值(例如:总利润)对它们进行排序时,它只返回 100,000 以下的数字(即 99,992.36,而实际上某些值达到数百万)。

当我切换到不同的关键值(例如:总成本)时,我遇到了同样的问题,但是如果该特定记录的总利润恰好超过 100,000,则该值会显示出来。所以我想我已经把它缩小到我的 sorted() 函数。

def processStats(originalList, header):

    #sorting in descending order
    sortedListByTotalProfit = sorted(originalList, key = operator.itemgetter(11), reverse = True)

    max_item = sortedListByTotalProfit[0]
    print(max_intem)

def main():
    fileName = 'Records.csv'
    records = []
    recordHeader = []    

    with open(fileName) as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            if i == 0: #first line is the header, store it in the list by splitting the first record by comma
                recordHeader=line.split(',') 
                continue
            records.append(line.split(",")) #takes each record in the file and stores elements separated by commas as elements of a list

    processStats(records, recordHeader)

【问题讨论】:

    标签: python sortedlist


    【解决方案1】:

    我猜数据类型是字符串。 您可以使用
    records.append(list(map(int, line.split(","))))替换records.append(line.split(","))
    所有代码:

    def processStats(originalList, header):
    
        #sorting in descending order
        sortedListByTotalProfit = sorted(originalList, key = operator.itemgetter(11), reverse = True)
    
        max_item = sortedListByTotalProfit[0]
        print(max_intem)
    
    def main():
        fileName = 'Records.csv'
        records = []
        recordHeader = []    
    
        with open(fileName) as f:
            lines = f.readlines()
            for i, line in enumerate(lines):
                if i == 0: #first line is the header, store it in the list by splitting the first record by comma
                    recordHeader=line.split(',') 
                    continue
                records.append(records.append(list(map(int, line.split(","))))) #takes each record in the file and stores elements separated by commas as elements of a list
    
        processStats(records, recordHeader)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2020-12-14
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2012-03-29
      相关资源
      最近更新 更多