Zouhair
Zouhair

Reputation: 43

How to sort this list in a specific way?


I have this list of some planets which shows:

This is my code:

planets = [('Mercury', 2440, 0.395),
           ('Venus', 6052, 0.723),
           ('Earth', 6378, 1),
           ('Mars', 3396, 1.53)]

# Name -- Radius (km) -- Distance from sun (AU)

print(*planets[0]), print(*planets[1]), print(*planets[2]), print(*planets[3])
# Printing planets (not in a sorted way), but without brackets, commas or apostrphes.

print('')

size = lambda planet: planet[1]
print(sorted(planets, key=size)) 
# I sorted the planets by radius

And the output is:

Mercury 2440 0.395
Venus 6052 0.723
Earth 6378 1
Mars 3396 1.53

[('Mercury', 2440, 0.395), ('Mars', 3396, 1.53), ('Venus', 6052, 0.723), ('Earth', 6378, 1)]

After sorting by radius, the output displays the commas, brackets, etc.
Instead of each time printing the planets individually, I would like to sort them directly just like the first output (of 4 lines).

Upvotes: 0

Views: 65

Answers (1)

CodeManX
CodeManX

Reputation: 11865

You can simply loop over the list of planets and print each element individually, similar to your first example:

planets = [('Mercury', 2440, 0.395),
           ('Venus', 6052, 0.723),
           ('Earth', 6378, 1),
           ('Mars', 3396, 1.53)]
           
size = lambda planet: planet[1]
for planet in sorted(planets, key=size):
    print(*planet)

Output:

Mercury 2440 0.395
Mars 3396 1.53
Venus 6052 0.723
Earth 6378 1

For descending radius make it sorted(planets, key=size, reverse=True).

Upvotes: 1

Related Questions