【发布时间】:2016-06-05 00:06:08
【问题描述】:
我对@987654322@ 中的if not 语句有疑问。
我已经编写了一些代码并使用了if not 语句。在我编写的代码的一部分中,我引用了一个函数,该函数包含一个if not 语句来确定是否输入了可选关键字。
它工作正常,除非0.0 是关键字的值。我理解这是因为0 是被认为是“不”的事物之一。我的代码可能太长,无法发布,但这是一个类似的(尽管是简化的)示例:
def square(x=None):
if not x:
print "you have not entered x"
else:
y=x**2
return y
list=[1, 3, 0 ,9]
output=[]
for item in list:
y=square(item)
output.append(y)
print output
但是,在这种情况下,我得到了:
you have not entered x
[1, 9, None, 81]
我想去哪里:
[1, 9, 0, 81]
在上面的示例中,我可以使用列表推导,但假设我想使用该函数并获得所需的输出,我该怎么做呢?
我的一个想法是:
def square(x=None):
if not x and not str(x).isdigit():
print "you have not entered x"
else:
y=x**2
return y
list=[1, 3, 0 ,9]
output=[]
for item in list:
y=square(item)
output.append(y)
print output
这可行,但似乎有点笨拙。如果有人有另一种很好的方式,我将非常感激。
【问题讨论】:
-
你可以通过 type "if type(x) != int:" 来查看
-
但是如果
0不是其中之一,您要过滤掉哪些值?您不能明确检查这些值吗? -
0 在布尔上下文中计算为 False。试试“如果 x 不是无”。
-
按参数类型重载的函数充其量只是一个可读性问题。更好的是
def square(x):和def square_vizier():,后者可能会调用前者。假设您阅读了y = square()行,现在您必须阅读 square 的定义才能看到它在您评论时确实使用了 query.vizier。显式优于隐式。 -
我只想指出
output=[]; for x in input: output.append(fn(x)模式几乎总是表明您应该使用map或理解。您的代码减去 square 函数只能是print map(square, [1, 3, 0, 9])或print [square(x) for x in [1,3,0,9]]。
标签: python python-2.7 if-statement control-structure