类型错误:"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)))

我认为这样的东西就可以了。

l1 = [75, 65, 35]
l2 = [75, 65, 35, 90]
def is_monotonoc(list1):
up=True
down=True
for i in range(len(list1)-1):
if not list1[i] <= list1[i+1]:
up=False
if not list1[i] >= list1[i+1]:
down=False
print(down or up)
is_monotonoc(l1)
is_monotonoc(l2)

只需捕捉@Matthis和@khelwood早期的想法,在这里总结一下:(当然,这要归功于他们(:[注意,如果需要strict的递减单调数组,那么只需将x <= y更改为x < y(或x > y(

def monotonic(lst):
''' check if the list is increasing or decreasing'''
if all(x <= y for x, y in zip(lst, itertools.islice(lst, 1, None))):
print('List is increasing monotonic list.')
elif all(x >= y for x, y in zip(lst, itertools.islice(lst, 1, None))):
print('List is decreasing monotonic list.')
else:
print('List is neither increasing nor decreasting monotonic list.')

输出:

>>> lst
[75, 65, 55, 40]
>>> monotonic(lst)
List is decreasing monotonic list.
'''

最新更新