我尝试在第一个条件上迭代 j。只有当第一个 if 语句对于 range(5) 中的每个 j 都不为真时,我才希望 j 迭代下一个条件。
一般问题:
my_list = []
for i in range(3):
for j in range(5):
if #condition == True:
#append something to my_list for only one j in range(5)
break # move on to the next i
elif #other condition == True:
#append something to my_list for only one j in range(5)
break # move on to the next i
例子:
my_list = []
for i in range(3):
for j in range(5):
if j == 3:
my_list.append(j)
break
elif j == 0:
my_list.append(j)
break
my_list
输出:[0, 0, 0]
我想要的输出:[3, 3, 3]
回答1
预期的逻辑并不完全清楚,但是IIUC,您想实现一种机制,您使用一个条件直到满足它,然后再更改为另一个?
您也许可以将单个比较与包含条件的列表一起使用?
my_list = []
for i in range(3):
conds = [3,0] # list of conditions
cond = conds.pop(0) # start with first one
for j in range(5):
if j == cond: # if condition is met
my_list.append(j) # store value
if conds: # if conditions are remaining
cond = conds.pop(0) # use the next one
else: # else terminate the sub-loop
break
输出:[3, 3, 3]