python排序列表,sorted()vs sort()

时间:2016-04-15 08:32:40

标签: python list

任何人都可以告诉为什么sort()在下面不起作用?谢谢 - 我在python 2中测试,并在

下面变得错误
res = a.index(x)
ValueError: 1 is not in list

详细代码:

a = [1, 3, 2, 5]

def f(y):
    print a

def fn(x):
    global a  # without `global`, you can still read variable `a` from outside
    print 'read a?'
    print a, type(a), id(a)
    res = a.index(x)
    return res

f(0)
a = sorted(a, key=fn)
print '----'
print a

print 'a.sort start'
a.sort(key=fn)  # a become [] ... no idea why!
print '----'
print a

0 个答案:

没有答案