我正在寻找内联工作的 list.extend() 方法的替代方法。
代替
x = range(15,30,3)
x.extend([0])
print (x)
>>> [15, 18, 21, 24, 27, 0]
我需要一个内联工作的等价物,比如
print range(15,30,3).extend([0])
>>> None
但是 extend 不返回列表本身。
是否有任何开箱即用的命令可以实现相同的目的?
最佳答案
只需使用 +
运算符连接这些列表:
range(15, 30, 3) + [0]
或者,如果您需要一个迭代器并且 list
很大,请使用 itertools.chain
:
import itertools
it = itertools.chain(range(15, 30, 3), [0])
快速说明:range
在 Python 3+ 中创建一个 range
对象,它不允许连接:
Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).
关于python - 扩展 Python 列表 "inline",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29058643/