我想检查一个列表是否只包含一个特定的元素(在我的例子中它没有)我相信有一种pythonic的方法,我试过: if mydict[direction] == None for direction in DIRECTIONS: ...但这显然不起作用换句话说,我需要一种 PYTHONIC 方式来缩短下一个代码:def ispure(element) for direction in DIRECTIONS: if mydict[direction] != element return False else: pass return True希望我很清楚,并提前致谢。
2 回答

浮云间
TA贡献1829条经验 获得超4个赞
最简单(但效率不高)的方法是: len(list(filter(lambda direction: mydict[direction] is not None, DIRECTIONS))) == 0
如果您想提高效率并且在列表中间某处条件为假的情况下不遍历所有元素,您可以使用takewhile
:
from itertools import takewhile
len(list(takewhile(lambda direction: mydict[direction] is not None, DIRECTIONS))) == len(DIRECTIONS)
添加回答
举报
0/150
提交
取消