如何按第n列Python对输出的文本文件进行排序

2024-04-30 04:04:52 发布

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

我的代码:

infile = open("ALE.txt", "r")
outfile = open("ALE_sorted.txt", "w")

for line in infile:
    data = line.strip().split(',')
    wins = int(data[2])
    percentage = 162 / wins
    p = str(data[0]) + ", " + data[1] + ", " + data[2] + ", " + 
str(round(percentage, 3)) + "\n"
    outfile.write(p)
infile.close()
outfile.close()

原始填充(“麦芽酒.txt“)只是下面的前三列。从上述代码输出的文本文件如下所示:

巴尔的摩,93,69,2.348
波士顿,69,93,1.742
纽约,95,67,2.418
坦帕湾,90,72,2.25
多伦多,73,89,1.82

我知道代码正确地计算了获胜百分比(第2列/总获胜数),但我想按第4列(获胜百分比)对列表进行排序。在


Tags: 代码txtforclosedatalineopeninfile
3条回答

首先,在处理这个问题时,最好使用线.分割(',').strip()。在

import csv
with open('ALE.txt', 'r') as infile:
    reader = csv.reader(infile)
    data = []
    for line in reader:
        formatted_line = [i.strip() for i in line]
        wins = int(formatted_line[2])
        percentage = 100*wins/total_wins
        formatted_line.append(str(round(percentage,3)))
        data.append(formatted_line)
    data = sorted(p, lambda x: x[3])
with open('ALE_sorted.txt', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    writer.writerows(data)

试试这个:

infile  = open("ALE.txt", "r")
outfile = open("ALE_sorted.txt", "w")

master_data = []

# Load in data from the infile and calculate the win percentage.
for line in infile:

    data = line.strip().split(', ')

    wins = int(data[2])
    percentage = 162 / wins
    data.append(str(round(percentage, 3)))

    master_data.append(data)

# Sort by the last column in reverse order by value and store the 
# sorted values and original indices in a list of tuples.
sorted_column = sorted([(float(data[-1]), index) for index, data in \
                        enumerate(master_data)], reverse = True)

# Reassign master_data according to the sorted positions.
master_data   = [master_data[data[1]] for data in sorted_column]

# Write each line to the outfile.
for data in master_data:

    outfile.write(str(", ".join(data) + "\n"))

infile.close()
outfile.close()

其中infile的内容如下:

^{pr2}$

结果outfile包含按新生成的第四列的值从高到低排序的以下内容:

New York, 95, 67, 2.418
Baltimore, 93, 69, 2.348
Tampa Bay, 90, 72, 2.25
Toronto, 73, 89, 1.82
Boston, 69, 93, 1.742

将数据追加到一个列表中,比如d。在

按列表的第三项(第4列)排序。引用-operator.itemgetter

将排序后的数据写入输出文件。在

输入文件的内容

[kiran@localhost ~]$ cat infile.txt
Baltimore, 93, 69
Boston, 69, 93
New York, 95, 67
Tampa Bay, 90, 72
Toronto, 73, 89

^{pr2}$

输出文件内容:

[kiran@localhost ~]$ cat outfile.txt
Boston, 69, 93,1.742
Toronto, 73, 89,1.82
Tampa Bay, 90, 72,2.25
Baltimore, 93, 69,2.348
New York, 95, 67,2.418

相关问题 更多 >