有没有一种pythonic的方法(我知道我可以使用range(len(..))循环并获取索引)来执行以下示例:
for line in list_of_strings:
if line[0] == '$':
while line[-1] == '#':
# read in the Next line and do stuff
# after quitting out of the while loop, the next iteration of the for loop
# should not get any of the lines that the while loop already dealt with
本质上,嵌套的while循环应递增for循环。
编辑:不是文件句柄,混淆了我正在处理的两件事,它是字符串列表
最佳答案
python中最基本的挑战之一是在list
和dict
上进行迭代时变得更聪明。如果实际上需要在迭代时修改集合,则可能需要处理副本,或存储更改以在迭代结束时应用。
不过,就您而言,您只需要跳过列表中的项目即可。您可能可以通过将迭代扩展为更明确的形式来进行管理。
i = iter(list_of_strings)
for line in i:
if line.startswith('$'):
while line.endswith('#'):
line = i.next()
# do work on 'line' which begins with $ and doesn't end with #
这就是您真正需要做的。
编辑:正如kindall所提到的,如果while部分可能迭代到输入序列的末尾,则您需要做更多的事情。您可以执行以下操作。
i = iter(list_of_strings)
for line in i:
if line[0] == '$':
try:
while line[-1] == '#':
line = i.next()
except StopIteration:
break
# do work on 'line' which begins with $ and doesn't end with #
关于python - python中的循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6834368/