<p>目前,您正在使用变量<code>i</code>作为<code>installed_tx_calc</code>中的字符串。但是,不能从字符串中减去。您真正想要的是使用<code>i</code>作为索引,并以这种方式进行访问:<code>installed_tx_calc[i]</code>。但是,如果要从列表中删除项,则使用索引可能会很棘手,因此我将for循环替换为while循环。另外,我建议您直接访问第一个数字,而不是获取切片。因此,您的代码看起来更像这样:</p>
<pre><code>i = 1
while i < len(installed_tx_calc):
if len(str(installed_tx_calc[i]) == 3 and str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]:
installed_tx_calc.remove(i)
continue
elif str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]:
installed_tx_calc.remove(i)
continue
i += 1
</code></pre>
<p>请记住,如果您有更多的长度不等于3或4的数字,这将打破。更具扩展性的解决方案是:</p>
<pre><code>i = 1
while i < len(installed_tx_calc):
if len(str(installed_tx_calc[i])) == len(str(installed_tx_calc[i-1])) and str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]:
installed_tx_calc.remove(i)
continue
i += 1
</code></pre>
<p>最后一个优化是避免使用<code>remove</code>来构建一个新的列表。^与<code>append</code>相比,{<cd5>}可能是一个相当慢的操作,因此以下操作将比前两种解决方案更快:</p>
<pre><code>new_itc = []
for i in range(1, len(installed_tx_calc):
if not (len(str(installed_tx_calc[i])) == len(str(installed_tx_calc[i-1])) and str(installed_tx_calc[i])[0] == str(installed_tx_calc[i-1])[0]):
new_itc.append(installed_tx_calc[i])
</code></pre>