有一个元组列表。我想根据元组的第二个值进行排序并返回两个列表的元组。
代码如下:
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])
答案 0 :(得分:0)
您可以先对元组列表进行排序,然后再将它们转换为列表元组。只需将 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。
答案 1 :(得分:0)
试试这个,函数会完成工作。我更改了您的 var col_def = [title:"TheJobSource", field:"JobCount", formatter: "progress", formatterParams:{legend: <dataField_string>}}
列表的测试值以表明它有效。
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))