排序列表和“for”语句snytax有问题

2024-06-01 01:55:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助从文本文件中排序列表。我正在读一个.txt文件,然后添加一些数据,然后按人口变化%对其排序,最后,将其写入一个新的文本文件。你知道吗

现在唯一给我带来麻烦的是排序函数。我认为for语句语法给了我一些问题——我不确定在代码中的什么地方添加sort语句,以及如何将其应用于for循环语句的输出。你知道吗

我试图排序的总体更改数据是列表中的[1]项。你知道吗

#Read file into script
NCFile = open("C:\filelocation\NC2010.txt")

#Save a write file
PopulationChange =
open("C:\filelocation\Sorted_Population_Change_Output.txt", "w")

#Read everything into lines, except for first(header) row
lines = NCFile.readlines()[1:]

#Pull relevant data and create population change variable
for aLine in lines:
    dataRow = aLine.split(",")
    countyName = dataRow[1]

    population2000 = float(dataRow[6])
    population2010 = float(dataRow[8])

    popChange = ((population2010-population2000)/population2000)*100
    outputRow = countyName + ", %.2f" %popChange + "%\n"
    PopulationChange.write(outputRow)


NCFile.close()
PopulationChange.close()

Tags: 数据txt列表forread排序语句file
2条回答

你可以通过一些小的改变来解决你的问题。在读入时拆分行,并在已排序的行上循环:

lines = [aLine.split(',') for aLine in NCFile][1:]

#Pull relevant data and create population change variable
for dataRow in sorted(lines, key=lambda row: row[1]):
    population2000 = float(dataRow[6])
    population2010 = float(dataRow[8])
    ...

但是,如果这是一个csv,您可能需要查看^{}模块。尤其是DictReader将根据标题行以字典列表的形式读入数据。我正在编下面的字段名,但你应该明白。您会注意到我在读入数据时根据'countryName'对数据进行排序:

from csv import DictReader, DictWriter

with open("C:\filelocation\NC2010.txt") as NCFile:
    reader = DictReader(NCFile)
    data = sorted(reader, key=lambda row: row['countyName'])

for row in data:
    population2000 = float(row['population2000'])
    population2010 = float(row['population2010'])
    popChange = ((population2010-population2000)/population2000)*100
    row['popChange'] = "{0:.2f}".format(popChange)

with open("C:\filelocation\Sorted_Population_Change_Output.txt", "w") as PopulationChange:
    writer = csv.DictWriter(PopulationChange, fieldnames=['countryName', 'popChange'])
    writer.writeheader()
    writer.writerows(data)

这将为您提供一个2列csv ['countryName', 'popChange']。您需要使用正确的字段名来更正此问题。你知道吗

您需要先读取文件中的所有行,然后才能对其进行排序。我创建了一个名为change的列表来保存人口变化和国家名称的元组对。此列表将被排序并保存。你知道吗

with open("NC2010.txt") as NCFile:
    lines = NCFile.readlines()[1:]
    change = []
    for line in lines:
        row = line.split(",")
        country_name = row[1]
        population_2000 = float(row[6])
        population_2010 = float(row[8])
        pop_change = ((population_2010 / population_2000) - 1) * 100
        change.append((pop_change, country_name))

    change.sort()
    output_rows = []
    [output_rows.append("{0}, {1:.2f}\n".format(pair[1], pair[0]))
                        for pair in change]
    with open("Sorted_Population_Change_Output.txt", "w") as PopulationChange:
        PopulationChange.writelines(output_rows)

我使用了一个列表理解来生成输出行,输出行按照所需的顺序(即首先是国家名称)交换成对的数据。你知道吗

相关问题 更多 >