我想找出最好的方法是什么:
resource['contents'][media_type] = []
resource['contents'][media_type].append(row[0].toPython()) if row[0] is not None else None
resource['contents'][media_type].append(row[2].toPython()) if row[2] is not None else None
我认为代码很简单;如果行有值,则将它们添加到列表中。这种方法可以吗?还有其他更好的方法吗? toPython
方法将返回包含对象的字符串描述。
最佳答案
使用“三元”conditional expression (x if C else y
) 对于副作用根本不是 Pythonic。以下是我的做法:
resource['contents'][media_type] = []
for index in (0, 2):
item = row[i]
if item is not None:
resource['contents'][media_type].append(item.toPython())
或使用列表理解来减少冗长:
resource['contents'][media_type] = [row[i].toPython() for i in (0, 2)
if row[i] is not None]
这些方法更具可读性,并且减少了重复。
关于python - 将条件表达式用于副作用是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32454225/