【问题标题】:List appears to be empty during sorting [duplicate]排序期间列表似乎为空[重复]
【发布时间】:2014-05-06 10:05:34
【问题描述】:

我想对列表进行就地排序,并尝试在排序期间使用列表本身(在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

对此有何解释?

【问题讨论】:

    标签: python list sorting


    【解决方案1】:

    来自listobject.c source code

    /* 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 documentation

    CPython 实现细节:在对列表进行排序时,尝试改变甚至检查列表的效果是未定义的。 Python 2.3 和更新版本的 C 实现使列表在持续时间内显示为空,如果它可以检测到列表在排序期间发生了变异,则会引发 ValueError

    您可以压缩ab

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

    【讨论】:

    • 那么 b.sort(key=lambda x: a[c.index(x)] 不应该在 c = b[:] 的地方工作吗?
    • @wnnmaw:也可以,是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2014-07-03
    • 2019-09-18
    • 2020-11-01
    • 2014-12-09
    • 2021-03-11
    相关资源
    最近更新 更多