[英]How do I skip certain elements in a list in a python for loop?
我有一个 for 循环,可以将列表中的数字相互比较,但我需要从比较中排除列表中的某些元素。 我需要从 for 循环中排除的元素的索引值位于一个名为 switch 的单独列表中:
switch = [451, 828, 1214, 1559, 1905, 2197, 2535, 2875, 3237, 3515, 3787, 4119, 4366, 4628, 4873, 5088, 5415, 5737, 6012, 6162, 6504, 6965, 7327, 7571, 7898, 8146, 8473, 8823, 9181, 9466, 9765, 10066, 10239, 10514, 10786, 10921, 11224, 11524, 11784, 12169, 12431, 12702]
我如何能够在我的 for 循环中跳过这些索引值? 谢谢你的帮助。
作为参考,这是我的 for 循环的一部分:
for index, lr in enumerate(choices[:-1]):
if choices[index] == 1:
if reward[index] == 1:
if choices[index + 1] == 1:
win_stay.append(1)
elif choices[index + 1] == 0:
win_stay.append(0)
elif reward[index] == 0:
if choices[index + 1] == 0:
lose_switch.append(1)
elif choices[index + 1] == 1:
lose_switch.append(0)
...
假设你的 for 循环的 rest 是正确的,这应该工作:
for index, lr in enumerate(choices[:-1]):
if index not in switch:
if choices[index] == 1:
if reward[index] == 1:
if choices[index + 1] == 1:
win_stay.append(1)
elif choices[index + 1] == 0:
win_stay.append(0)
elif reward[index] == 0:
if choices[index + 1] == 0:
lose_switch.append(1)
elif choices[index + 1] == 1:
lose_switch.append(0)
if index not in switch:
部分只是确保索引不在您的列表switch
中。
您可以检查您当前的索引是否在您的跳过列表中。
skip = [1,3]
letters = ['a','skip1','b','skip2','c']
correct = []
for index,letter in enumerate(letters):
if index not in skip:
correct.append(letter)
output:
['a', 'b', 'c']
您可以使用continue 语句。
for index, lr in enumerate(choices[:-1]):
if index in switch:
continue
# rest of your code here
itertools 模块有 filterfalse 可能在这里有用:
from itertools import filterfalse
leave_out = [2, 3, 4, 5]
filter_it = lambda x: x in leave_out
for i in filterfalse(filter_it, range(10)):
print(i)
0
1
6
7
8
9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.