python 3的布尔参数
这个问题我需要使用elif吗?我该怎么做呢? 很抱歉问你这个问题python 3的布尔参数,python,python-3.x,Python,Python 3.x,这个问题我需要使用elif吗?我该怎么做呢? 很抱歉问你这个问题 def hint1(p1, p2, p3, p4): ''' (bool, bool, bool, bool) -> bool Return True iff at least one of the boolen parameters p1, p2, p3, or p4 is True. >>> hint1(False, True, False, True) Tr
def hint1(p1, p2, p3, p4):
''' (bool, bool, bool, bool) -> bool
Return True iff at least one of the boolen parameters
p1, p2, p3, or p4 is True.
>>> hint1(False, True, False, True)
True
'''
你可以试试
def hint1(p1,p2,p3,p4):
if p1 or p2 or p3 or p4:
return True
或
尽可能地短
def hint1(p1,p2,p3,p4):
return any([p1,p2,p3,p4])
该方法接受单个iterable,如果任何元素为true,则返回true
def hint1(p1, p2, p3, p4):
return any([p1, p2, p3, p4])
该函数接受一个iterable,若其中的任何元素为True,则返回True
def hint1(p1, p2, p3, p4):
return any([p1, p2, p3, p4])
问题是any
接受一个iterable,而不是一组单独的值
这就是*args
的作用。它接受所有参数,并将它们放在一个元组中,该元组被输入到单个参数中。然后,您可以将该元组作为iterable传递给any
。有关详细信息,请参见教程中的
正如Elazar指出的,这并不适用于4个参数,它适用于任意数量的参数(甚至0)。这是好是坏取决于您的用例 如果希望在3个参数或5个参数上出现错误,当然可以添加一个显式测试:
if len(args) != 4:
raise TypeError("The number of arguments thou shalt count is "
"four, no more, no less. Four shall be the "
"number thou shalt count, and the number of "
"the counting shall be four. Five shalt thou "
"not count, nor either count thou three, "
"excepting that thou then proceed to four. Six "
"is right out.")
但实际上,对于这种情况,只使用静态参数列表要简单得多。或
返回p1或p2或p3或p4
。但是任何
都是正确的选择。谢谢!我还没有在课堂上学习任何函数,所以这是最有帮助的<代码>def hint1(*args):返回任何(args)认真地说,提供了哪些学习材料?这是一个基本问题,您的学习材料应该包含您需要的答案。hint1=lambda*x:any(x)
。较短:P+1,与原始问题有一个区别-它没有强制执行“4个参数”。@Elazar:但原始问题没有在任何地方说明该要求。+1-对于使用*args
我不知道它是否是实际要求,但从技术上讲它是-通过参数列表。
if len(args) != 4:
raise TypeError("The number of arguments thou shalt count is "
"four, no more, no less. Four shall be the "
"number thou shalt count, and the number of "
"the counting shall be four. Five shalt thou "
"not count, nor either count thou three, "
"excepting that thou then proceed to four. Six "
"is right out.")