最后一次迭代后闭合范围的Pythonic方法

2024-10-01 02:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码风格的问题,我正在寻找一个pythonic实现我写了下面。你知道吗

我发布的(简化的)代码遍历一个序列并返回范围。每个范围以特定条件开始和结束。范围不能重叠。我使用一个变量active来跟踪是否已经找到范围的开始。如果序列末尾的活动范围尚未关闭,则应添加它(以input_length作为结束索引)

下面的代码按预期工作,但我不喜欢这样一个事实,即我必须编写代码将范围附加到结果列表两次。在我遇到的实际问题中,这个块要长得多,我不想在for循环之后再写一次。你知道吗

你有什么建议我可以改进这个吗?你知道吗

谢谢!你知道吗

input_length = 100
results = []

active = False
start = None
for i in range(input_length):
    condition = i % 9 == 0
    if not active and condition:
        active = True
        start = i

    condition2 = i % 13 == 0
    if active and condition2:
        active = False
        # do some additional calculations...
        results.append((start, i))

if active:
    # do some additional calculations...
    results.append((start, input_length))

print(active)
print(results)

Tags: and代码falseforinputif序列some
2条回答

简单的方法是编辑内部条件:

    condition2 = i % 13 == 0
    if active and (condition2 or i == input_length-1))
        active = False
        # do some additional calculations...
        results.append((start, i if condition2 else i + 1))

并拆下外部。你知道吗

如果你想避免i if condition2 else i + 1,也许你可以迭代range(input_length + 1)?(这取决于你在循环中做的其他事情)

我找到了一个很好的方法:

import itertools as it

il = 100
results = []
def fun1():
    active = False
    start = None
    for i in range(il):
        condition = i % 9 == 0
        if not active and condition:
            active = True
            start = i
        condition2 = i % 13 == 0
        if active and condition2:
            active = False
            # do some additional calculations...
            results.append((start, i))
    if active:
        # do some additional calculations...
        results.append((start, il))
    return results

def fun2():
    a=b=0
    while b<il:
        yield (a,b)
        b=b+13
        a=a+9
        while a<=b-13:
            a=a+9
    if a<il:
        yield (a,il)

print fun1()
print
print [(a,b) for (a,b) in fun2()]

请检查代码中il的不同值,并在使用之前将其与您的函数进行比较。你知道吗

相关问题 更多 >