此调用链接在python中合法吗?

问题描述 投票:1回答:1

我对下面的python代码的行为感到困惑。我想对列表中的最后3个数字进行排序。但是,当我链接操作时,它不起作用。我想念什么?

行为1:

>>> a = [10,4,2,3]
>>> b = a[1:].sort() # I want to sort last 3 numbers. But when I chain the 
                     # operations, it doesn't work. Why?
>>> b
<empty value> 

====

行为2:

>>> a = [10,4,2,3]
>>> b = a[1:]
>>> b.sort()
>>> b
[2, 3, 4]
python syntax
1个回答
0
投票

这是因为.sort()不会返回新列表,而是会更改现有列表。例如。 [5, 2, 7, 4, 5].sort()不返回任何内容。看看这个:

a = [2, 4, 7, 3, 4, 6]
a.sort()
print(a)

输出为:

[2, 3, 4, 4, 6, 7]

您可能要这样做:

a = [2, 4, 7, 3, 4, 6]
b = sorted(a[1:])
print(a)
print(b)
© www.soinside.com 2019 - 2024. All rights reserved.