<p>这是一种快速的方法:</p>
<pre><code>lst1 = [1, 2, 3, 4, 5, 6, 7, 8]
new_list = [*lst[:4], *[x+2 for x in lst1[4:]]]
# or even better
new_list[4:] = [x+2 for x in lst1[4:]]
</code></pre>
<p>就速度而言,对于这么小的列表,numpy并不是更快:</p>
<pre><code>import timeit
import numpy as np
lst1 = [1, 2, 3, 4, 5, 6, 7, 8]
npa = np.array(lst)
def numpy_it():
global npa
npa[4:] += 2
def python_it():
global lst1
lst1 = [*lst1[:4], *[x+2 for x in lst1[4:]]]
print(timeit.timeit(numpy_it))
print(timeit.timeit(python_it))
</code></pre>
<p>对我来说:</p>
<pre><code>1.7008036
0.6737076000000002
</code></pre>
<p>但是对于任何严肃的numpy,它都比为需要替换的片段生成一个新的列表要好得多,这比重新生成整个列表要好得多(这比使用循环进行就地替换要好得多,如您的示例中所示):</p>
<pre><code>import timeit
import numpy as np
lst1 = list(range(0, 10000))
npa = np.array(lst1)
lst2 = list(range(0, 10000))
lst3 = list(range(0, 10000))
def numpy_it():
global npa
npa[4:] += 2
def python_it():
global lst1
lst1 = [*lst1[:4], *[x+2 for x in lst1[4:]]]
def python_it_slice():
global lst2
lst2[4:] = [x+2 for x in lst2[4:]]
def python_inplace():
global lst3
for i in range(4, len(lst3)):
lst3[i] = lst3[i] + 2
n = 10000
print(timeit.timeit(numpy_it, number=n))
print(timeit.timeit(python_it_slice, number=n))
print(timeit.timeit(python_it, number=n))
print(timeit.timeit(python_inplace, number=n))
</code></pre>
<p>结果:</p>
<pre><code>0.057994199999999996
4.3747423
4.5193105000000005
9.949074000000001
</code></pre>