现在,我相信我的函数是不正确的,因为我得到了超过1个布尔输出。
listOstrings = ['cat in the hat','michael meyers','mercury.','austin powers','hi']
def StringLength(searchInteger, listOstrings):
'return Boolean value if the strings are shorter/longer than the first argument'
for i in listOstrings:
if len(i) < searchInteger:
print(False)
else:
print(True)发布于 2019-04-15 23:03:59
您不希望为每一项打印True或False;您希望在循环迭代过程中创建一个布尔值。或者更简单地说,只要发现一个未通过测试的元素,就可以返回False,只有在整个循环中没有返回的情况下才返回True。
def checkStringLength(searchInteger, lstStrings):
'return Boolean value if the strings are shorter/longer than the first argument'
for i in lstStrings:
if len(i) < searchInteger:
return False
return True使用all函数可以更自然地编写以下代码:
def checkStringLength(searchInteger, lstStrings):
return all(len(i) >= searchInteger for i in lstStrings)https://stackoverflow.com/questions/55691821
复制相似问题