【发布时间】:2015-05-24 01:13:05
【问题描述】:
一个函数正在接收许多都是字符串但需要以各种方式解析的值,例如
vote_count = int(input_1)
score = float(input_2)
person = Person(input_3)
这一切都很好,除了输入也可以是None,在这种情况下,我不想解析值,而是将None分配给左侧。这可以通过
vote_count = int(input_1) if input_1 is not None else None
...
但这似乎不太可读,尤其是像这样的许多重复行。我正在考虑定义一个简化这一点的函数,比如
def whendefined(func, value):
return func(value) if value is not None else None
可以像这样使用
vote_count = whendefined(int, input_1)
...
我的问题是,这有什么通用的成语吗?可能使用内置的 Python 函数?即使没有,这样的函数有常用的名称吗?
【问题讨论】:
-
你已经拥有的 (
whendefined) 在我看来很好。 -
只是好奇 - 为什么
vote_count是 None 比分配0更好?感觉后续代码中的 if 数量会更少。 -
顺便说一句,由于您的输入始终是字符串,您可以将表达式缩短为
vote_count = int(input_1) if input_1 else None。 (如果input_= "",这也会产生None) -
@thefourtheye 只是想知道标准库中是否有我错过的任何解决方案。另外我想知道是否有比
whendefined更好的名字。 -
@Nsh 有时需要显式建模缺失值。