Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何对列表进行插入排序?_Python_Algorithm_Sorting_Python 3.x_Insertion Sort - Fatal编程技术网

Python 如何对列表进行插入排序?

Python 如何对列表进行插入排序?,python,algorithm,sorting,python-3.x,insertion-sort,Python,Algorithm,Sorting,Python 3.x,Insertion Sort,上面我有一些代码可以对列表进行排序,例如 def insertionSort(mylist): for index in range(1, len(mylist)): currentvalue = mylist[index] position = index while position > 0 and mylist[position - 1] > currentvalue: mylist[position] = mylist[position

上面我有一些代码可以对列表进行排序,例如

def insertionSort(mylist):
for index in range(1, len(mylist)):
    currentvalue = mylist[index]
    position = index
    while position > 0 and mylist[position - 1] > currentvalue:
        mylist[position] = mylist[position - 1]
        position = position - 1
    mylist[position] = currentvalue
return mylist
屈服

list1 = [(12,45,62),(78,35,72),(34,52,75)]
insertionSort(list1)

它按第一个元素(12、34和78)对每个子列表进行排序。如何按子列表的第二个和第三个元素对插入排序?

Python库中的排序函数为此提供了一个
key
参数,确定用于获取用于比较两个元素的键的函数。您可以对自己的插入排序执行相同的操作。此参数的默认值可以是返回元素本身的函数,但可以使用任何其他键函数重写它

list1 = [(12,45,62),(34,52,75),(78,35,72)]
示例:

def insertionSort(mylist, key=lambda x: x):
    for index in range(1, len(mylist)):
        currentvalue = mylist[index]
        position = index
        while position > 0 and key(mylist[position - 1]) > key(currentvalue):
            mylist[position] = mylist[position - 1]
            position = position - 1
        mylist[position] = currentvalue
    return mylist

注意:在
排序
排序
中,对于列表中的每个值,
函数将只评估一次,而在此版本中,它将针对每次比较进行评估。如果只想调用该函数一次,例如,可以将键值缓存在字典中。

您坚持使用插入排序有什么原因吗?@AnthonyLabarre在这种情况下这有关系吗?太棒了。谢谢你的回答
>>> list1 = [(12,45,62),(78,35,72),(34,52,75)]
>>> insertionSort(list1)
[(12, 45, 62), (34, 52, 75), (78, 35, 72)]
>>> insertionSort(list1, key=lambda x: x[1])
[(78, 35, 72), (12, 45, 62), (34, 52, 75)]