Reputation: 33
So I have a text file which contains "Name", "Surname" "Age" with multiple lines of data.
I have been able to extract the "Age" from the file and been able to put it from oldest to youngest. The only problem now is that I want to display all the people from the list but in order from oldest to youngest while showing their name and surname.
I also have separate variables for each of the lines. For example Name1 = "John", "Doe", "16". Name2 = "Doe", "John", "16". I know this is a bad way of doing it but I have no clue what to do.
and Age = [24,14,16]
Without the qoutes
I thought of
if Age[2] in Name1[2]:
#John Doe is 16
But the problem is when I add the points extracted from the file to a list it shows like this [14,25,25]
instead of ["14","25", "25"]
.
Since its "25" on the variable and 25 on the age list.
This is my first time posting on here so I'm sorry if my formatting is wrong or I make no sense at all on my post. Feel free to message me I would be more than happy to explain further.
Thanks for reading, hope you can help. Also if you have any solutions for what to do in terms of my hardcoding the Name1, please let me know too.
Upvotes: 1
Views: 105
Reputation: 512
You can use a list of dicts (one dict for one user):
users = [{'name':'john','surname':'doe','age':16}, ...{...}]
for order your list of dicts by age you can use:
newlist = sorted(users, key=lambda k: k['age'])
Upvotes: 2
Reputation: 601
You can create a dataframe from your textfile with columns "Name", "Surname" "Age".
Then use data.sort_values(by=['Age'],ascending=False) of pandas which will automatically return the required result.
Upvotes: 0
Reputation: 483
One easy solution is to parse Age[2] to string.
str(Age[2]) in Name1
Since Name1 = "John", "Doe", "16" will return a tuple. So "in" operator can be used with Name1 without specifying the index.
Upvotes: 0