我可以为for循环添加条件吗?

时间:2014-07-10 02:42:19

标签: python

说我有类似的东西:

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'):

4 个答案:

答案 0 :(得分:5)

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

<强>实施

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

<强>输出

banana
carrot
dragonfruit

答案 1 :(得分:4)

for str_ in (s for s in array if s[0].lower() not in 'aeiou'):
    print(str_)

不要使用str,因为它会影响内置字符串构造函数。

那说这看起来更像是一个正则表达式而不是列表补偿。

import re

words = ['apple', 'banana', 'carrot', 'dragonfruit', 'eggplant']
pat = re.compile(r'''
        \b            # Begin a word
        [^aeiou\s]\w* # Any word that doesn't begin with a vowel (or a space)
        \b            # End a word''', re.X)
matches = re.findall(pat, ' '.join(words), re.I)
print(matches)

没关系,我无法让它工作,现在没有时间去处理它。我在正则表达式上失败了:(

这让我感到非常困扰。我修好了。

答案 2 :(得分:2)

startswith((&#39; A&#39;&#39; E&#39;&#39; I&#39;&#39; O&#39;&#39; U&#39; )basestring.join()列表理解永远是你成为Pythonic的好朋友:)

你可以使用这个:

no_vowels = [str for str in array if not str.startswith(('a','e','i','o','u'))]
for nv in no_vowels:
  print nv

或者这个:

print '\n'.join([str for str in array if not str.startswith('a','e','i','o','u'))] 

答案 3 :(得分:2)

您可以使用list comprehension,其内容类似于您在问题中建议的内容。

请注意str&#39; str在一开始和&#39;如果&#39;而不是&#39;其中&#39;。

另请注意,字符串是可迭代的,因此您可以将if语句简化为:     如果x [0] .lower()不在&#39; aeiou&#39;

因此,一个简单的解决方案可能是:

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

#filter out fruit that start with a vowel
consonant_fruit = [fruit for fruit in all_fruit if fruit[0].lower() not in 'aeiou']

for tasty_fruit in consonant_fruit:
    print tasty_fruit

或者你可以使用更高效的内存生成器表达式,这个例子中唯一的变化是&#39; []&#39;到&#39;()&#39;

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

#filter out fruit that start with a vowel
consonant_fruit = (fruit for fruit in all_fruit if fruit[0].lower() not in 'aeiou')

for tasty_fruit in consonant_fruit:
    print tasty_fruit

还有filter内置:

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

for tasty_fruit in filter(lambda fruit: fruit[0].lower() not in 'aeiou', all_fruit):
    print tasty_fruit