简体   繁体   中英

Sorting a list of list/tuple by element at a certain index

How would I start sorting this list so that it displays the names of the countries in order, determined by the conversion rate (it involves reading data from a text file)? I want it to display only the name of the countries, and not the exchange rate. Additionally, I'm a novice, so the simpler answer the more helpful and the better I can understand/learn. I'm not sure if I'd call this a list or a dictionary.

America,Dollar,1
Argentina,Peso,8.257
Australia,Dollar,1.432
Austria,Euro,0.82

I have a general idea about how to start, but I don't know what to do from here. Here's what I have so far:

fhand = open('Exchange.txt')
for line in fhand:
    line = line.split(',')
print line[0]

The outputs should be something like:

Austria
Australia
America
Argentina

Something like this should work:

all_data = []

fhand = open('/tmp/data')

for line in fhand:
    data_parts = line.strip().split(',')
    # Convert the data to a tuple of country and the exchange rate as
    # a number (rather than a string).
    data_item = (data_parts[0], float(data_parts[2]))
    all_data.append(data_item)
fhand.close()

# Sort that data by the 2nd part of the tuple: the exchange rate
all_data.sort(key = lambda x: x[1])
# print out the sorted list but only print the first part: the country
for di in all_data:
    print(di[0])

Sort the list of rates.

data = """America,Dollar,1
Argentina,Peso,8.257
Australia,Dollar,1.432
Austria,Euro,0.82"""

rates = [line.split(",") for line in data.split("\n")]

print rates
sorted_rates = sorted(rates, key=lambda x: float(x[2]))
print sorted_rates

Output:

[['America', 'Dollar', '1'], ['Argentina', 'Peso', '8.257'], ['Australia', 'Dollar', '1.432'], ['Austria', 'Euro', '0.82']]
[['Austria', 'Euro', '0.82'], ['America', 'Dollar', '1'], ['Australia', 'Dollar', '1.432'], ['Argentina', 'Peso', '8.257']]

This should be easiest to understand for you.

# Read the file content, as a single string into "file_content"
file_content = open('Exchange.txt').read()
print(file_content)

# Prints:
# America,Dollar,1
# Argentina,Peso,8.257
# Australia,Dollar,1.432
# Austria,Euro,0.82


# Split the file contents to lines, which is a list of strings,
# each element of list being a single line of the file
lines = file_content.splitlines()
print(lines)

# Prints:
# ['America,Dollar,1', 'Argentina,Peso,8.257', 'Australia,Dollar,1.432', 'Austria,Euro,0.82']


# Split each line into 3 parts, separated by comma
split_lines = [line.split(',') for line in lines]
print(split_lines)

# Prints:
# [['America', 'Dollar', '1'], ['Argentina', 'Peso', '8.257'], ['Australia', 'Dollar', '1.432'], ['Austria', 'Euro', '0.82']]


# Sort the complete list using the third element of each sublist as the key to sort
lines_sorted = sorted(split_lines, key=lambda x: x[2])

for line in lines_sorted:
    print(line[0])

Final loop prints:

Austria
America
Australia
Argentina

Note: if sorted according to exchange rates, the expected output given in the question is a bit wrong. Check it out for yourself.


Useful links, specifically for the OP ;-) :

This might be inefficient and I don't close the file after reading either... But hey, one line! :D

print("\n".join((z[1] for z in sorted(((float(x[2]), x[0]) for x in (line.split(",") for line in open('Exchange.txt')))))))

A more reasonable solution...

with open("Exchange.txt", "r") as f:
    for li in sorted((float(x[2]), x[0]) for x in (line.split(",") for line in f)):
        print li[1]

Look, ma', no loops!

with open("Exchange.txt", "r") as f:
    data = map(lambda x: x.split(","), f.readlines())
    data = map(lambda x: (float(x[2]), x[0]), data)
    print "\n".join(map(lambda x: x[1], sorted(data)))

This one goes out to @zondo ;)

with open("Exchange.txt", "r") as f:
    data = []
    for line in f:
        data.append(line.split(","))
    data = sorted(data, key=lambda x: float(x[2]))
    for line in data:
        print line[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM