Python 如何将元组转换为列表并应用点表示法

问题描述 投票:0回答:3

为什么:

x = (5,4,3)
y = list(x)
y.sort()

工作,但是

x = (5,4,3)
y = list(x).sort()

不工作?

python casting dot-notation
3个回答
1
投票
y = list(x)

这会在

list
上调用函数
x
并将结果放入 y

y = list(x).sort()

这会在

list
上调用函数
x
,在结果列表上调用
.sort()
,然后将 .sort()
 的返回值存储在 
y
 中,
.sort()
 的返回值为 
None

列表在内存中排序,但排序后的列表被丢弃,只有

None

 存储在 
y
 中。


1
投票
Python 中的

sort()

 方法对列表中的元素进行就地排序并返回 
None

当你做类似的事情时:

y = list(x).sort()
您可以使用包含元组 x 的已排序元素的 

sorted()

y = sorted(x)
    

0
投票
在第二种情况下,仅使用

list(x).sort()

代替
y = list(x).sort()
应该可以工作,因为您无法“存储”排序方法的结果。

© www.soinside.com 2019 - 2024. All rights reserved.