在Python中压缩多个条件 [英] Compressing multiple conditions in Python
问题描述
假设我有一个数字列表 mylist
,并且如果 mylist
的所有元素都大于10,我想执行一些代码.我可以尝试
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
但这显然很麻烦.我想知道Python是否可以在if语句中压缩多个条件.我尝试过
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.
我正在使用Python 3.4.
I am using Python 3.4.
推荐答案
您的尝试非常接近.您只需要 all
函数来检查表达式的结果.
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):
这篇关于在Python中压缩多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!