列表理解和“全部”关键字

nums = ['90']

print(all([((ele == ele[::-1] and int(ele) > 0) for ele in nums)]))

我期望上面的代码能够打印False,但它正在打印True。您能解释一下打印的原因吗?


阿波罗的战车
浏览 78回答 1
1回答

慕少森

((ele == ele[::-1] and int(ele) > 0) for ele in nums)是你的生成器,但是你将其包装在一个 list 中[((ele == ele[::-1] and int(ele) > 0) for ele in nums)]。因此,您要传递的all是:[<generator&nbsp;object&nbsp;<genexpr>&nbsp;at&nbsp;0x059BE070>]在这种情况下一切都会返回true。你想要的是:print(all(((ele&nbsp;==&nbsp;ele[::-1]&nbsp;and&nbsp;int(ele)&nbsp;>&nbsp;0)&nbsp;for&nbsp;ele&nbsp;in&nbsp;nums)))或者print(all([(ele&nbsp;==&nbsp;ele[::-1]&nbsp;and&nbsp;int(ele)&nbsp;>&nbsp;0)&nbsp;for&nbsp;ele&nbsp;in&nbsp;nums]))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python