[英]TypeError: 'bool' object is not iterable when using 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
what is wrong here?
You must have some kind of iterable sequence of items inside the all
call.您必须在
all
调用中有某种可迭代的项目序列。 I think you want to get rid of the for-loop and write it into generator expressions inside the all
calls.我认为您想摆脱 for 循环并将其写入
all
调用中的生成器表达式。
So where you have:所以你在哪里:
for i in range(len(list1)-1):
print(all(list1[i] <= list1[i+1]) or all(list1[i] >= list1[i+1]))
you mean你的意思是
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)))
Something like this would do the trick I think.像这样的东西会做我认为的伎俩。
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)
Just capture @Matthis and @khelwood earlier ideas to summarize here: (credit to them, of course): [Note, if the strict
in/de-creasing monotonic array is required, then just change x <= y
to x < y
(or x > y
)只需捕获@Matthis 和@khelwood 早期的想法在这里总结:(当然归功于他们):[注意,如果需要
strict
的 in/de-cresing 单调数组,那么只需将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.')
Outputs:输出:
>>> lst
[75, 65, 55, 40]
>>> monotonic(lst)
List is decreasing monotonic list.
'''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.