有一个元组列表。我想根据元组的第二个值进行排序,并返回一个包含两个列表的元组
代码如下:
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])
尝试此操作,该函数将完成此工作。我更改了
artists
列表的测试值,以表明它是有效的输出:
在将元组列表转换为列表元组之前,可以对它们进行排序。只需添加
x.sort(key = lambda x: x[1], reverse=False)
作为函数的第一行,如下所示有关更多信息和其他选项,请选中here
相关问题 更多 >
编程相关推荐