python - 遍历 not None 和 not empty 目录

标签 python python-3.x list directory

给定两个目录,例如,

dirA=getTrainingDir()
dirB=getTestingDir()

现在我想遍历这两个目录,如果它们不是 None 也不是空字符串的话

我现在做的是:

data_directories=[]
if dirA:
  data_directories.append(dirA)
if dirB:
  data_directories.append(dirB)
for data_directory in data_directories:
  ...

为此目的还有更优雅的语法吗?

最佳答案

没有更好的方法来做到这一点,但你可以使用这样的东西:

if any([dirA,dirB])

或:

data_directories=[di for di in [dirA,dirB]  if di]

关于python - 遍历 not None 和 not empty 目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50249025/

相关文章:

python - Python 中的条件嵌套循环

python - 将列表附加到字典以获取嵌套列表

c++ - 子集化后将包含索引号的列表映射到标准索引序列

python - NOT NULL 约束在 Flask + SQLite3 中失败

python - Matplotlib 直方图(基础题)

python - 将 MySql 数据库值拉入列表存储 - Python3 和 Mysql.connector

python - 使用 Python 和 datetime 模块根据 TimeUUIDType 从 Cassandra 获取列范围

python - 如何在 PyQt5 中拥有动态字段?

c# - 如何检查对象列表是否包含具有指定属性的对象

c# - 按属性对对象列表进行分组,分成多个列表。