循环,但使用Python的某些值除外

循环,但使用Python的某些值除外,python,Python,我正在运行一个循环,如下所示: 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]):

我正在运行一个循环,如下所示:

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)
我想对
范围(len(sections))
中的一些值运行循环。例如,除值12、13、55、67和70外,该范围内涵盖的所有值

我知道我可以把范围分成几个部分,但我很想写下数字。有什么建议吗?

使用

您可以从以下位置使用该功能:

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
# 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
这只能用于迭代所需的条目,跳过不需要的值。它将显示以下内容:

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)
tax 1
税项2
税项3
税项4
税项5
税6
税项7
税项8
税项9
税项10
税项11
税项14
税15
税项16
税17
税项18
税项19
税20
税项21
税项22
税项23
税24
税25
税项26
税项27
税项28
税29
税30
税项31
税项32
税项33
税收34
税项35
税36
税项37
税项38
税项39
税40
税项41
税项42
税项43
税项44
税45
税项46
税收47
税项48
税49
税50
税项51
税项52
税务53
税54
税收56
税务57
税项58
税项59
税60
税收61
税项62
税63
税64
税65
税66
税项68
税69
税项71
税收72
税项73
税项74
税75
税项76
税项77
税项78
税项79

或者只使用
枚举
中,如下所示:

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
# 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

非常感谢你的回答。看起来真不错。然而,难道没有更简单的事情吗?我可以在循环的第一部分做一些事情:对于范围内的I(len(部分)跳过12、13等)?您可以只使用
枚举
中的
,我已经更新了解决方案。但是
ifilterfalse
可能会更快。