我有一个代码风格的问题,我正在寻找一个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)
简单的方法是编辑内部条件:
并拆下外部。你知道吗
如果你想避免
i if condition2 else i + 1
,也许你可以迭代range(input_length + 1)
?(这取决于你在循环中做的其他事情)我找到了一个很好的方法:
请检查代码中il的不同值,并在使用之前将其与您的函数进行比较。你知道吗
相关问题 更多 >
编程相关推荐