排序过程中列表似乎为空[重复]

发布于 2021-01-29 14:57:10

这个问题已经在这里有了答案

在排序时访问列表 (2个答案)

6年前关闭。

我想就地对列表进行排序,并尝试在排序过程中(key功能内)使用列表本身。我发现列表本身似乎是空的。

a = [1,4,5,3,2,6,0]
b = ['b', 'e', 'f', 'd', 'c', 'g', 'a']
b.sort(key=lambda x: a[b.index(x)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
ValueError: 'b' is not in list

所以我尝试了:

def f(x):
  print "FOO:", x, b
  return b.index(x)

b.sort(key=f)

并得到

FOO: b []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
ValueError: 'b' is not in list

有什么解释吗?

关注者
0
被浏览
60
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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).
     */
    

    并从Mutable Sequence
    Types文档中

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

    您可以压缩ab改为:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看