【发布时间】:2021-06-16 07:24:12
【问题描述】:
在 python 3.0 中,我目前正在尝试使用我的插入排序算法按第二个元素(第一个索引)对我拥有的列表列表进行排序。 例如,我想按照第二个元素的值降序排列这样的列表。
预排序:
list = [ ["Name1", 10.0, 9.5, 8.6, 4.0],
["Name2", 14.5, 9.1, 4.2, 0.6],
["Name3", 9.9, 42.0, 9.1, 4.1],
.....]
后排序:
list = [ ["Name2", 14.5, 9.1, 4.2, 0.6],
["Name1", 10.0, 9.5, 8.6, 4.0],
["Name3", 9.9, 42.0, 9.1, 4.1],
.....]
我目前的插入排序方法是这样的:
def sort_points(a_list):
"""Sorts in descending order."""
for index in range(1, len(a_list)):
value = a_list[index][1]
pos = index - 1
while pos >= 0 and a_list[pos][1] < value:
a_list[pos + 1] = a_list[pos]
pos -= 1
a_list[pos + 1] = value
当我尝试运行代码时,出现以下错误:
Traceback(最近一次调用最后一次):
sort_points(allstars_2021)
File "C:/Users/Michael/PycharmProjects/NBAstats/CompareStats.py", line 16, in sort_points
while pos >= 0 and a_list[pos][1] < value:
TypeError: 'float' object is not subscriptable
不确定我在这里做错了什么,因为我调整了我之前使用浮点值的插入排序算法,但从未在列表列表中对元素进行排序的场景中。任何帮助将不胜感激,谢谢!
【问题讨论】:
-
你能给出准确的输入列表吗?因为当我尝试使用您提供的列表时,它会返回另一个列表为
[14.5, ['Name1', 10.0, 9.5, 8.6, 4.0], 9.9],以防万一,如果您有递归或尝试在同一个列表上运行相同的函数,您可能会遇到这个问题。
标签: python algorithm sorting software-design