我正在创建的代码的最后部分遇到问题。例如,我试图使列表正常地迭代到项目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
A for
循环不是必需的。如果您对使用第3方库感到满意,可以使用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]
您正在将i的值设置为for循环内的某个值。在for循环的每次迭代开始时,python都将i的值更新为要迭代的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()
[您想做的事实际上不是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