如何按三列对文本文件进行排序,并按特定顺序对Python中的这些列进行排序? [英] How do I sort a text file by three columns with a specific order to those columns in Python?

查看:154
本文介绍了如何按三列对文本文件进行排序,并按特定顺序对Python中的这些列进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I sort a text file by three columns with a specific order to those columns in Python?

我的text_file的格式如下,各列之间有空格:

My text_file is in the following format with whitespaces between columns:

Team_Name Team_Mascot Team_Color Team_Hometown Number_of_Wins Team_Coach

示例:

Bears LittleBear Blue Beartown 15 BigBear

我想按升序对它进行排序,首先是Team_Color,第二是Team_Hometown,然后是Number_of_Wins.

I want to sort it by Team_Color first, Team_Hometown second, and Number_of_Wins third in ascending order.

因此,属性:

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

我的预期输出是经过排序的文本文件:

My expected output is a sorted text file:

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

I have thought about using lambda but none of my values are a tuple https://docs.python.org/3/tutorial/controlflow.html

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

I have looked at previous StackOverflow questions but most of them dealt with sorting two columns at maximum using lambda, tuple, or other methods

推荐答案

您的问题仍然模棱两可.您的示例的标题中没有引入第一个字段Team_Name.因此,这里的索引可能是一个索引,但我认为您可以理解这个概念:

Your question is still ambiguous. Your example doesn't have the first field Team_Name introduced in your header. So the index here is probably off by one, but I think you get the concept:

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

这篇关于如何按三列对文本文件进行排序,并按特定顺序对Python中的这些列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆