擅长:python、mysql、java
<p>这里已经有了很好的答案,但是您可以用一种不必硬编码模式的方式来编写代码</p>
<p>将操作类型和增量作为参数,可以执行以下操作:</p>
<pre><code>test_list2 = [1,3,5,7,9,20,21,22]
result = 0
operation = "+"
increment = 2
for n, i in enumerate(test_list2):
if n < len(test_list2) - 1:
if eval(f'{test_list2[n]}{operation}{increment}') == test_list2[n+1]:
result = test_list2[n+1]
print(result)
</code></pre>
<p>实际上,我突然想到,只有在跳转后模式发生变化时,代码才会返回正确的值。如果您希望能够检测到跳转,即使之后模式保持不变,您必须打破循环:</p>
<pre><code>test_list2 = [1,3,5,7,9,20,21,22]
result = 0
operation = "+"
increment = 2
i = 0
while i < len(test_list2) - 1:
if eval(f'{test_list2[i]}{operation}{increment}') == test_list2[i+1]:
result = test_list2[i+1]
else:
break
i += 1
print(result)
</code></pre>