且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

排序过程中列表似乎为空

更新时间:2023-11-30 23:46:58

来自 listobject.c源代码:

/* The list is temporarily made empty, so that mutations performed
 * by comparison functions can't affect the slice of memory we're
 * sorting (allowing mutations during sorting is a core-dump
 * factory, since ob_item may change).
 */

,并来自可变序列类型文档:

CPython实现细节:在对列表进行排序时,尝试更改甚至检查列表的效果是不确定的. Python 2.3及更高版本的C实现使该列表在整个持续时间内都显示为空,并且如果它可以检测到该列表在排序过程中发生了突变,则抛出ValueError.

CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python 2.3 and newer makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.

您可以改为压缩ab:

b[:] = [bval for (aval, bval) in sorted(zip(a, b))]