Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

python - Sort a list of tuples according to the 2nd value of the tuples

Have a list of tuples. I want to sort according to the 2nd value of the tuples and return a tuple of two lists.

Here is the code:

def sort_artists(x):
    artist = []
    earnings = []
    z = (artist, earnings)
    for inner in x:
        artist.append(inner[0])
        earnings.append(inner[1])
    return z

artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))

Desired output is

(['Elvis Presley', 'Michael Jackson', 'The Beatles'], [270.8, 211.5, 183.9])

Output which i get is,

(['The Beatles', 'Elvis Presley', 'Michael Jackson'], [270.8, 211.5, 183.9])
question from:https://stackoverflow.com/questions/65832767/sort-a-list-of-tuples-according-to-the-2nd-value-of-the-tuples

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this, the function will do the work. I changed the test values of your artists list to show that it works.

def sort_artists(x):
    artist = []
    earnings = []
    for inner in x:
        artist.append(inner[0])
        earnings.append(inner[1])
    index = sorted(range(len(earnings)), key=lambda k: earnings[k])
    artist = [artist[i] for i in index]
    earnings = [earnings[i] for i in index]
    z = (artist, earnings)
    return z

artists = [("The Beatles", 250), ("Elvis Presley", 530), ("Michael Jackson", 120)]
print(sort_artists(artists))

Output:

(['Michael Jackson', 'The Beatles', 'Elvis Presley'], [120, 250, 530])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...