0

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
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Rob
  • 35
  • 4
  • So you want to print the names of the countries in an order based on the lowest to highest conversion rates of the countries? – user_loser May 01 '16 at 17:22
  • dictionary data structures are built to not be sortable. Check out this answer to a similar question: http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value – user_loser May 01 '16 at 17:28
  • @Rob try now with my code, I've added the sort – Milor123 May 01 '16 at 17:36
  • ahhhhhhhh ok ok, what is the order? euro>dollar>peso ?? – Milor123 May 01 '16 at 17:45
  • @Milor123 just the countries, i want to order it by the exchange rate, but have only the countries show up in the output – Rob May 01 '16 at 17:50
  • 1
    Sorted w.r.t. rates, your output should be Austria>America>Australia>Argentina. If this is so, take a look at my answer. – Sнаđошƒаӽ May 01 '16 at 17:52
  • Possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – Sнаđошƒаӽ May 02 '16 at 02:27

4 Answers4

3

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])
Oliver Dain
  • 9,617
  • 3
  • 35
  • 48
1

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 works on my box too. Nice coding @Display Name :) It is very pythonic in how few lines of code it took to do this too. – user_loser May 01 '16 at 18:00
  • This does not read from a file like OP has though... It kind of does not meet the specification on this minor point. – user_loser May 01 '16 at 18:02
  • @user_loser True, but this is complete, runable code. This us more useful for future readers than an answer to an incomplete question. –  May 01 '16 at 18:10
1

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 ;-):

Community
  • 1
  • 1
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
1

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]
jDo
  • 3,962
  • 1
  • 11
  • 30
  • 2
    There are so many parentheses and `for`'s, etc. that this is very hard to read. Your "more reasonable" solution is still not very reasonable. "Simple is better than complex" does not mean "shorter is better than longer". – zondo May 01 '16 at 20:20
  • @zondo When I write an apologetic preamble in which I point out the errors in my code up-front and finish it with a big smiley, it typically means that what follows isn't too serious. I meant *"more reasonable"* in relation to the "joke" solution and to the file closing/opening (none of the other solutions used `with` which was surprising). Regarding all the quasi-buddhist python speak, I think it's too ambiguous to make much sense, really. I want to program, not find inner peace!? That being said, I agree that "readability counts" and here I've failed miserably! :D – jDo May 01 '16 at 21:12
  • @zondo Better now? – jDo May 02 '16 at 00:26
  • 1
    Yep. Looks great. – zondo May 02 '16 at 00:27