Compressing multiple conditions in Python

时光总嘲笑我的痴心妄想 提交于 2021-02-10 08:57:42

问题


Suppose I have a list of numbers mylist and that I would like execute some code if all the elements of mylist are greater than 10. I might try

if mylist[0] > 10 and mylist[1] > 10 and ... :
    do something

but this is obviously very cumbersome. I was wondering if Python has a way of compressing multiple conditions in an if statement. I tried

if mylist[i] > 10 for i in range(len(mylist)):
    do something

but this returned an error.

I am using Python 3.4.


回答1:


Your attempt is pretty close. You just needed the all function to examine the results of the expression.

if all(mylist[i] > 10 for i in range(len(mylist))):
    do something

Incidentally, consider iterating over the items of the list directly, rather than its indices.

if all(item > 10 for item in mylist):



回答2:


Do it like this

if all(x > 10 for x in myList):



回答3:


The answer is all:

if all(item > 10 for item in mylist):
   do something


来源:https://stackoverflow.com/questions/29370317/compressing-multiple-conditions-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!