<p>试试这个:</p>
<pre><code>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()
</code></pre>
<p>其中<code>infile</code>的内容如下:</p>
^{pr2}$
<p>结果<code>outfile</code>包含按新生成的第四列的值从高到低排序的以下内容:</p>
<pre><code>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
</code></pre>