Skip to main content
 首页 » 编程设计

python之我可以在 for 循环中添加条件吗

2025年05月04日13me-sa

假设我有类似的东西:

array = ['apple', 'banana', 'carrot', 'dragonfruit', 'eggplant'] 

现在我想打印这个数组中的值,其中值不以元音开头。

即

banana 
carrot 
dragonfruit  

我能做到:

for str in array: 
    if str[0].lower() not in ('a','e','i','o','u'): 
        print str 

我想知道的是,是否有一种 pythonic 的方式来表达类似这样的话:

for str in array where str[0].lower() not in ('a','e','i','o','u'): 

请您参考如下方法:

你知道吗str.startswith接受前缀元组?

实现

for fruit in (elem for elem in array  
              if not elem.startswith(('a','e','i','o','u'))): 
    print fruit 

输出

banana 
carrot 
dragonfruit