问题
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