我正在创建一个代码的最后一部分的问题。例如,我试图使列表正常迭代到第3项,但然后检查项目是否为3和其他条件(现在无关紧要),然后将索引更改为从示例10迭代。
我做了很多尝试,但它似乎没有用。
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in range(0,len(li)):
print(i)
if i == 3: #along with other condition
def g(li):
global i
i = li[9]
g()
print(i)
你可以使用continue
声明:
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in range(len(li)):
if 3 <= i < 10: #along with other condition
continue
print(i)
打印时输出i
:
0,1,2,10,11,12,13,14,15
打印时输出li[i]
:
1,2,3,11,12,13,14,15,16
continue
语句会在循环开始时引导您,忽略以下所有条件。
你可能想看看loop control statements
您将i的值设置为for循环内的某个值。在for循环的每次迭代开始时,python将i的值更新为迭代的迭代中的下一个值。因此,您的价值会丢失而不会被使用。
一种解决方案是使用另一个变量(skip_until),如下所示:
lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
skip_until = -1
for i in range(len(lst)):
if i == 3:
skip_until = 9
if skip_until >= i:
continue
print((i, lst[i]))
输出:
(0, 1) (1, 2) (2, 3) (10, 11) (11, 12) (12, 13) (13, 14) (14, 15) (15, 16)
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
condition3_reached = False
condition10_reached = False
for i in li:
print(i)
if conditition3_reached and not condition10_reached and i != 10:
continue
if condition3_reached and i == 10:
condition10_reached = True
if i == 3 and (#along with other condition):
condition3_reached = True
print(i)
else:
do_some_new_thing_for_10_onwards()
这是实现您想要的简单方法。我担心它不具备可扩展性
应该像这样继续使用:
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for i in range(0,len(li)):
if i in range(3, li[9]):
continue
print(i)
实现这一目标的最简单和可读的方法是使用while
而不是for
循环,如下所示。
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
i = 0
while i < len(li):
print(i)
if i == 3:
i = 10
print(i)
i += 1 # increment i at the end of the loop
我试着理解你说的话,我写了这段代码
li = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
def k(pos = 0):
for i in li[pos:]:
print(i)
if li.index(i) == 3: #along with other condition
return k(pos = 9)
k()
不需要for
循环。如果您对使用第三方库感到满意,可以使用NumPy:
import numpy as np
A = np.array(li)
res = A[np.r_[:4, 9:len(A)]]
# array([ 1, 2, 3, 10, 11, 12, 13, 14, 15, 16])
或者使用常规Python,您可以使用slice
对象:
from operator import itemgetter
from itertools import chain
slices = (slice(0, 4), slice(9, None))
res = list(chain.from_iterable(itemgetter(*slices)(li)))
# [1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16]
使用Python for
循环,你想要做的事情是不可能的,它比Java / C风格的for (initializer; step; condition)
循环更少,但更像是foreach (iterable)
循环,其中可迭代恰好是你的情况下的range
。
因此,无论何时在循环中执行i = ...
(i
是for
循环中的变量),i
将在循环的下一次迭代中使用新值覆盖(未修改)。
相反,您可以使用稍长的while
循环:
i = 0
while i < len(li):
print(i)
if i == 3: #along with other condition
def g(li):
global i
i = li[9]
g(li)
else:
i += 1
另请注意,嵌套函数g
显然没有任何用途,可以删除,尽管实际代码中的情况可能有所不同。
i = 0
while i < len(li):
print(i)
if i == 3: #along with other condition
i = li[9]
else:
i += 1