您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 动态构建布尔表达式

5b51 2022/1/14 8:23:27 python 字数 3006 阅读 576 来源 www.jb51.cc/python

我正在编写一些代码来增加文件名末尾的数字,直到它不再覆盖现有文件.我正在创建几个文件,所有文件都具有相同的基本文件名但不同的扩展名,我都不想覆盖它们. 朴素版: prefix = 'hello0' while os.path.exists(prefix + '.abc') or os.path.exists(prefix + '.def') or os.path.exists(prefix + '

概述

朴素版:

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 – 动态构建布尔表达式所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶