我正在运行以下循环:
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'Novemeber', 'December']
for i in range(len(sections)):
if (' tax ' in sections[i]
or ' Tax ' in sections[i]):
pat=re.compile("|".join([r"\b{}\b".format(m) for m in months]), re.M)
month = pat.search("\n".join(sections[i].splitlines()[0:6]))
print(month)
我想为值range(len(sections))
运行循环,除了其中一些。例如,除了值12,13,55,67和70之外,范围内涵盖的所有值。
我知道我可以将范围分成几部分,但我很乐意只通过编写数字来实现。有什么建议吗?
答案 0 :(得分:2)
for index, element in enumerate(some_list):
if index in range(1, 20):
print("Element: {0} with index {1} in first range".format(element, index))
elif index in [82, 111]:
print("Element: {0} with index {1} in second range".format(element, index))
答案 1 :(得分:2)
您可以使用ifilterfalse
中的itertools
功能,如下所示:
from itertools import ifilterfalse
# Build an example list of sections, e.g. sections = [' tax 1', ' tax 2' ....., ' tax 79']
sections = [" tax {}".format(i) for i in range(1, 80)]
# Entries to skip over
skip = [12, 13, 55, 67, 70]
for index, value in ifilterfalse(lambda (i, v): i in skip, enumerate(sections, start=1)):
print value
这可以用于仅迭代所需的条目,跳过您不需要的值。它将显示以下内容:
tax 1
tax 2
tax 3
tax 4
tax 5
tax 6
tax 7
tax 8
tax 9
tax 10
tax 11
tax 14
tax 15
tax 16
tax 17
tax 18
tax 19
tax 20
tax 21
tax 22
tax 23
tax 24
tax 25
tax 26
tax 27
tax 28
tax 29
tax 30
tax 31
tax 32
tax 33
tax 34
tax 35
tax 36
tax 37
tax 38
tax 39
tax 40
tax 41
tax 42
tax 43
tax 44
tax 45
tax 46
tax 47
tax 48
tax 49
tax 50
tax 51
tax 52
tax 53
tax 54
tax 56
tax 57
tax 58
tax 59
tax 60
tax 61
tax 62
tax 63
tax 64
tax 65
tax 66
tax 68
tax 69
tax 71
tax 72
tax 73
tax 74
tax 75
tax 76
tax 77
tax 78
tax 79
或者仅使用enumerate
和in
,如下所示:
# Build an example list of sections, e.g. sections = [' tax 1', ' tax 2' ..... ' tax 79']
sections = [" tax {}".format(i) for i in range(1, 80)]
for index, value in enumerate(sections, start=1):
if index not in [12, 13, 55, 67, 70]:
print value