Bas*_*asj 1 python loops code-duplication while-loop
我想找到第一个myfile????.txt尚不存在的文件名(???? 是一个数字).这有效:
import os
i = 0
f = 'myfile%04i.txt' % i
while os.path.exists(f):
i += 1
f = 'myfile%04i.txt' % i
Run Code Online (Sandbox Code Playgroud)
但我不喜欢代码重复f = ....
是否有一种pythonic方法来避免此while循环中的代码重复?
注意:我已经发布了一个半满意的解决方案,使用do/while成语,如在Python中模拟一个do-while循环的主要答案中所提到的那样?,但我仍然想知道这种特殊情况是否有更好的方法(因此,这不是这个问题的愚蠢).
你不需要在while这里遵循paradiagm,一个带有next()作品的嵌套生成器表达式:
import os
from itertools import count
f = next(f for f in ('myfile%04i.txt' % i for i in count()) if not os.path.exists(f))
print(f)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |