问题描述
编辑:感谢您对如何完成我正在尝试做的事情的友好回复,但问题是关于为什么 range().append() 返回如果您一步尝试,则没有,为什么如果您分两步操作,它会起作用.
我正在尝试创建一个数字列表,但稍有不同.我不想在列表的开头输入几个数字:
mlist = [0, 5, 6, 7, ...]
所以我想这样做:
mlist = range(5,n+1).append(0)
但无声地失败,因为 type(mlist)
之后等于 NoneType
?!(相关:type(range(5,10)
计算结果为 list
Type)
如果我尝试分两步完成,例如:
.通过将返回值分配给mlist
,而不是您想要构建的列表.这是一个标准的 Python 习惯用法;改变可变对象的方法永远不会返回改变的对象,总是None
.将两个步骤分开:
mlist = range(5, n + 1)mlist.append(0)
这将 [0]
添加到 end;如果您在开始时需要 0
,请使用:
mlist = [0] + range(5, n + 1)
或者你可以使用 list.insert()
,再次作为一个单独的调用:
mlist = range(5, n + 1)mlist.insert(0, 0)
但后者必须将所有元素向上移动一步,通过连接创建一个新列表对于较短的列表是更快的选择,插入在较长的列表中胜出:
>>>从时间导入时间>>>定义连接(n):... mlist = [0] + range(5, n)...>>>定义插入(n):... mlist = range(5, n)... mlist.insert(0, 0)...>>>timeit('concat(10)', 'from __main__ import concat')1.2668070793151855>>>timeit('insert(10)', 'from __main__ import insert')1.4820878505706787>>>timeit('concat(1000)', 'from __main__ import concat')23.53221583366394>>>timeit('insert(1000)', 'from __main__ import insert')15.84601092338562EDIT: Thank you for your kind replies on how to accomplish what I am trying to do, but the question is about WHY range().append() returns None if you try it in one step, and WHY it works if you two-step the procedure.
Im trying to create a numerical list but with a twist. I don't want a couple of numbers at the beggining of my list:
mlist = [0, 5, 6, 7, ...]
So i thought to do the following:
mlist = range(5,n+1).append(0)
but silently fails because type(mlist)
afterwards equals to NoneType
?! (related: type(range(5,10)
evaluates to list
Type)
If i try to do that in two steps eg:
>>> mlist = range(5,10)
#and then
>>> mlist.append(0)
>>> mlist
[5, 6, 7, 8, 9, 10, 0]
What's happening?
list.append()
alters the list in place, and returns None
. By assigning you assigned that return value to mlist
, not the list you wanted to build. This is a standard Python idiom; methods that alter the mutable object never return the altered object, always None
.
Separate the two steps:
mlist = range(5, n + 1)
mlist.append(0)
This adds [0]
to the end; if you need the 0
at the start, use:
mlist = [0] + range(5, n + 1)
or you can use list.insert()
, again as a separate call:
mlist = range(5, n + 1)
mlist.insert(0, 0)
but the latter has to shift up all elements one step and creating a new list by concatenation is the faster option for shorter lists, insertion wins on longer lists:
>>> from timeit import timeit
>>> def concat(n):
... mlist = [0] + range(5, n)
...
>>> def insert(n):
... mlist = range(5, n)
... mlist.insert(0, 0)
...
>>> timeit('concat(10)', 'from __main__ import concat')
1.2668070793151855
>>> timeit('insert(10)', 'from __main__ import insert')
1.4820878505706787
>>> timeit('concat(1000)', 'from __main__ import concat')
23.53221583366394
>>> timeit('insert(1000)', 'from __main__ import insert')
15.84601092338562
这篇关于附加到范围函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!