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

2024/11/19 16:32:45

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

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

Example:

Bears LittleBear Blue Beartown 15 BigBear

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

Therefore the attributes:

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

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

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

Answer

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")
https://en.xdnf.cn/q/119927.html

Related Q&A

regular expression to search only one-digit number

Im trying to find sentences having only one digit number along with.sentence="Im 30 years old." print(re.match("[0-9]", sentence)then it returns<re.Match object; span=(0, 1), mat…

Automate adding new column and field names to all csv files in directories [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 3…

Connect the python app to a database using centos 7

I am new to all this I have apython app already helo.mysql.py and need to Connect the python app to a database. I am using centos 7 and have it installed on a ec2 instance if anyone can help please he…

How do I restart my program in Python? (see code)

if option == C:radius = float(raw_input("Enter Radius: ")) area = pi * radius**2print "Working..."sleep(1)print ("Area: %.2f. \n%s" % (area, hint))elif option == T:base = …

how to create a list of elements from an XML file in python

my XML <root> - <Book category="Children"><title>Harry Potter</title> <author>J.K</author> <year>2005</year> <price>29.99</price> &…

Is random.sample truly random?

I have a list with 155k files. When I random.sample(list, 100), while the results are not the same from the previous sample, they look similar. Is there a better alternative to random.sample that retur…

how to extract a table column data present in pdf and stored inside a variable python

I have 3 tables (image pasted) all 3 table(have same columns) look same and i want data of address column (yellow colour) of 3 tables stored inside a variable.

Pong Created in Python Turtle

Im new to Python but Ive coded in other languages, mainly for hardware. I made pong in Python using turtle but its a little glitchy. I was wondering if any of you could check it out and give advice. I …

How to build a Neural Network with sentence embeding concatenated to pre-trained CNN

I want to build a neural network that will take the feature map from the last layer of a CNN (VGG or resnet for example), concatenate an additional vector (for example , 1X768 bert vector) , and re-tra…

Obtaining values from columns in python

I want to obtain the top 3 cities and items based on their sales, but the only thing I can do now is return the all cities and items with their respective sales. Without using dict, can I obtain my des…