在Python中,如何按三列的特定顺序对文本文件进行排序?

2024-05-14 14:45:56 发布

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

在Python中,如何按三列的特定顺序对文本文件进行排序?你知道吗

我的文本文件采用以下格式,列之间有空格:

Team_Name Team_Mascot Team_Color Team_Hometown Number_of_Wins Team_Coach

示例:

Bears LittleBear Blue Beartown 15 BigBear

我想先按球队的颜色排序,然后按球队的家乡排序,最后按球队获胜的次数排序。你知道吗

因此,属性:

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

我曾考虑过使用lambda,但没有一个值是元组 https://docs.python.org/3/tutorial/controlflow.html

我看过以前的StackOverflow问题,但大多数问题都是使用lambda、tuple或其他方法对最多两列进行排序


Tags: 排序blueredteambears文本文件球队coach1
2条回答

您可以使用itemgetter模块中的operator来完成:

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")

输出(使用showList):

['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']

新文件中的输出格式:

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

你的问题仍然模棱两可。您的示例没有在标题中引入第一个field Team\u名称。所以这里的索引可能偏离了1,但我认为你得到了一个概念:

#read lines of text file and split into words
lines = [line.split() for line in open("test.txt", "r")]
#sort lines for different columns, numbers converted into integers to prevent lexicographical sorting
lines.sort(key = lambda x: (x[1], x[2], int(x[3])))
#writing the sorted list into another file
with open("new_test.txt", "w") as f:
    for item in lines:
        f.write(" ".join(item) + "\n")

相关问题 更多 >

    热门问题