python - TypeError: 'bool' 对象在使用 all() 时不可迭代
问题描述
我的代码只是检查列表是单调递增还是递减。我收到以下错误,TypeError Traceback (most recent call last)
<ipython-input-64-63c9df4c7243> in <module>
10 l1 = [75, 65, 35]
11 l2 = [75, 65, 35, 90]
---> 12 is_monotonoc(l)
<ipython-input-64-63c9df4c7243> in is_monotonoc(list1)
1 def is_monotonoc(list1):
2 for i in range(len(list1)-1):
----> 3 print(all(list1[i] <= list1[i+1]) or all(list1[i] >= list1[i+1]))
4
5 def isMonotonic(A):
TypeError: 'bool' object is not iterable
这里有什么问题?
解决方案
all
您必须在调用中有某种可迭代的项目序列。我认为您想摆脱 for 循环并将其写入all
调用中的生成器表达式。
所以你在哪里:
for i in range(len(list1)-1):
print(all(list1[i] <= list1[i+1]) or all(list1[i] >= list1[i+1]))
你的意思是
print(all(list1[i] <= list1[i+1] for i in range(len(list1)-1))
or all(list1[i] >= list1[i+1] for i in range(len(list1)-1)))