python – 动态构建布尔表达式

python – 动态构建布尔表达式,第1张

概述我正在编写一些代码来增加文件名末尾的数字,直到它不再覆盖现有文件.我正在创建几个文件,所有文件都具有相同的基本文件名但不同的扩展名,我都不想覆盖它们. 朴素版: 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 thiscondition = Truewhile 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)
解决方法 您可能希望使用带有生成器的any()内置:
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 – 动态构建布尔表达式所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1207578.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存