概述
朴素版:
prefix = 'hello0' while os.path.exists(prefix + '.abc') or os.path.exists(prefix + '.def') or os.path.exists(prefix + '.ghi'): n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1) # I kNow this doesn't work when n reaches two digits; my full code involves a regular expression
当有超过几个扩展时,这种情况显然会变得非常漫长和丑陋.我把它抽象为for循环.
我的版本:
prefix = 'hello0' extensions = ('.abc','.def','.ghi') # there Could be even more than this condition = True while condition: condition = False # if any of the paths still exist,set the condition back to True for extension in extensions: if os.path.exists(prefix + extension): condition = True n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1)
我仍然觉得这有点笨拙:还不完全清楚while循环实际上是在测试什么.是否可以动态构建布尔表达式,而不是设置布尔值?
我认为以下可能有用(我没有测试过,我只是在写这篇文章的时候才想到它!)但是我认为我不应该求助于eval:
prefix = 'hello0' extensions = ('.abc','.ghi') test = 'False' for extension in extensions: test += " or os.path.exists(prefix + '" + extension + "')" while eval(test): n = int(prefix[-1]) prefix = prefix[:-1] + str(n + 1)
while any(os.path.exists(prefix + extension) for extension in extensions): # then increment prefix and try again,as in your example code
这会使用更简单的语法计算您需要的True或False.
一般来说,如果我觉得在Python这样的动态语言中使用eval()的诱惑,那就意味着我需要了解一个重要的语言特性.动态语言应该使代码变得美观,而不会出现编写和维护代码的灾难 – 编写更多代码 – 所以你在这里通过询问你的方法做了正确的事情.
总结
以上是编程之家为你收集整理的python – 动态构建布尔表达式全部内容,希望文章能够帮你解决python – 动态构建布尔表达式所遇到的程序开发问题。
如果您也喜欢它,动动您的小指点个赞吧