排序列表在python中无法正常工作

时间:2019-05-31 02:48:00

标签: python sortedlist

我正在排序一个包含14个标题和500,000条记录的csv文件。我使用枚举功能对它们进行了组织。但是,当我使用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)

1 个答案:

答案 0 :(得分:0)

我猜数据类型是字符串。 您可以使用
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)