gpt4 book ai didi

python - Python 中的每个项目长度

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:22 25 4
gpt4 key购买 nike

我试图定义一个函数,如果列表中的每一项都小于 2 则返回 true,否则返回 false。项目的类型可以是整数、 float 、字符串或不同于列表的其他类型。我应该检查列表。

def ifeveryitems(lst):
for items in lst:
if isinstance(items,list) and len(items) <= 2:
return True and ifeveryitem(????) # '????' should be the items other than the item that has been searched #
else:
return False

最佳答案

根据您的描述,您根本不需要递归调用:

def ifeveryitems(lst):
for items in lst:
if isinstance(items, list) and len(items) > 2:
return False

return True

或者,或者:

def ifeveryitems(lst):
return all(len(items) <= 2 for items in lst if isinstance(items, list))

关于python - Python 中的每个项目长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14417870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com