Skip to main content
 首页 » 编程设计

python之以两个(或更多)其他变量为条件指定 `str` 的更优雅方式

2025年05月04日25haluo1

我想指定一个以其他两个变量为条件的 str(将用作文件名)。假设我有一个基本名称(指定为 str 类型),file_name = 'filename.txt';我有两个变量,x 和 y,它们可以是 NoneType 或 str。我期望的可以通过以下代码实现:

if x == None and y == None: 
    file_name = 'filename.txt' 
elif x == 'abc' and y == None: 
    file_name = 'filename_abc.txt' 
elif x == None and y == 'def': 
    file_name = 'filename_def.txt' 
else: # both x and y are str 
    file_name = 'filename_{}_{}.txt'.format(x, y) 

所以基本上,如果 x(或 y)是一个非 NoneType str,则 _ 中应该有一个额外的下划线 文件名。我可以理解使用 if 和 elif 语句可以达到目的。但是,如果有两个以上(比如 10 个)条件变量,如 x 和 y 怎么办?这将是相当冗长的。我想知道是否有更优雅的方式来做到这一点。

请您参考如下方法:

这个怎么样?

bits = [s for s in (x, y) if not s is None] 
file_name = '_'.join(['filename'] + bits) + '.txt'