<p>您可以使用<code>itemgetter</code>模块中的<code>operator</code>来完成:</p>
<pre><code>from operator import itemgetter
def showList(inList):
for i in inList:
print(i)
lines = []
with open("test.txt", "r") as infile:
lines = [i.split() for i in infile.readlines()]
lines = [[int(j) if j.isdigit() else j for j in i] for i in lines]
showList(lines)
lines = sorted(lines, key=itemgetter(1,2,3))
print()
showList(lines)
with open("output.txt", "w") as outfile:
for line in lines:
outfile.write(" ".join(str(i) for i in line) + "\n")
</code></pre>
<p>输出(使用<code>showList</code>):</p>
<pre><code>['Bears', 'Blue', 'Beartown', 15, 'Coach1']
['Bears', 'Red', 'Dogtown', 30, 'Coach6']
['Bears', 'Blue', 'Cattown', 15, 'Coach2']
['Bears', 'Red', 'Beartown', 15, 'Coach4']
['Bears', 'Blue', 'Cattown', 17, 'Coach3']
['Bears', 'Red', 'Dogtown', 9, 'Coach5']
['Bears', 'Blue', 'Beartown', 15, 'Coach1']
['Bears', 'Blue', 'Cattown', 15, 'Coach2']
['Bears', 'Blue', 'Cattown', 17, 'Coach3']
['Bears', 'Red', 'Beartown', 15, 'Coach4']
['Bears', 'Red', 'Dogtown', 9, 'Coach5']
['Bears', 'Red', 'Dogtown', 30, 'Coach6']
</code></pre>
<p>新文件中的输出格式:</p>
<pre><code>Bears Blue Beartown 15 Coach1
Bears Blue Cattown 15 Coach2
Bears Blue Cattown 17 Coach3
Bears Red Beartown 15 Coach4
Bears Red Dogtown 9 Coach5
Bears Red Dogtown 30 Coach6
</code></pre>