如何知道命令或方法是否是“就地算法"? [英] How to know if a command or method is an 'in place algorithm'?
问题描述
我正在学习 python,我怎么知道命令或方法是否是 '到位算法' ?
尝试大"输入并使用命令检查运行时是否是一个足够好的指标?
例如,假设我有一个包含 100,000 个元素的列表 lst
.我检查了以下两个命令并且都完成"了:lst = lst[ : :-1]
和 lst.reverse()
.那么这是否意味着两者都已就位?
就地操作在 Python 中通常返回 None
,所以在你的情况下 lst.reverse()
是一个就地操作,因为它返回 None
并修改列表.lst[::-1]
返回一个您重新分配给 lst
的新列表.
I'm learning python, how can I know if a command or method is an 'in place algorithm' ?
Does trying 'big' inputs and checking the runtime with the command a good enough indicator ?
For example, say I have a list lst
with 100,000 elements.
I checked the following two commands and both 'finished' in a moment: lst = lst[ : :-1]
and lst.reverse()
. So does that mean that both are in place ?
In-place operation usually return None
in Python, so in your case lst.reverse()
is an in-place operation as it returns None
and modifies the list as well. While lst[::-1]
returns a new list that you re-assigned to lst
.
>>> lst = range(1000)
>>> id(lst)
154457996
>>> lst = lst[::-1]
>>> id(lst) #id changed.
160699852
>>> lst = range(1000)
>>> id(lst)
160699340
>>> lst.reverse()
>>> id(lst) #same id
160699340
这篇关于如何知道命令或方法是否是“就地算法"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!