根据元组的第二个值对元组列表进行排序

2024-05-17 19:44:08 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个元组列表。我想根据元组的第二个值进行排序,并返回一个包含两个列表的元组

代码如下:

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

期望输出为

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

我得到的输出是

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

Tags: the列表排序artistsort元组innerappend
2条回答

尝试此操作,该函数将完成此工作。我更改了artists列表的测试值,以表明它是有效的

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

输出:

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

在将元组列表转换为列表元组之前,可以对它们进行排序。只需添加x.sort(key = lambda x: x[1], reverse=False)作为函数的第一行,如下所示

# your function
def sort_artists(x):
# sorts tuples by second value (x[1]), if reverse=True it will sort descending
    x.sort(key = lambda x: x[1], reverse=False)  
    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)]

# call your function
list_artists = sort_artists(artists)

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

有关更多信息和其他选项,请选中here

相关问题 更多 >