擅长:python、mysql、java
<p>只需使用enumerate并从第二个元素开始使用每个元素:</p>
<pre><code>def diffr(h, myList):
d = []
for ind, n in enumerate(myList[1:],1): # first iteration n will be the second element and myList[ind-1]) will be the first
d_elem = (n - myList[ind-1]) / h
d.append(d_elem)
return d
</code></pre>
<p>您不需要指定<code>myList = []</code>作为参数,您将传入一个列表并使用<code>list</code>作为默认参数通常不是一个好主意<a href="https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">“Least Astonishment” in Python: The Mutable Default Argument</a></p>
<p>在<code>for ind, n in enumerate(myList[1:],1)</code>中,<code>ind</code>是每个元素的索引,我们添加<code>1</code>作为参数指定从<code>index 1</code>开始,因此<code>n</code>将是<code>myList[ind-1])</code>前面的一个元素</p>
<p>在您的代码中,您使用元素来索引,因此,如果您的列表有4个元素,并且第一个数字是4或更大,那么您将尝试访问列表中不存在的索引处的元素,并立即出现索引错误。你知道吗</p>