2024-05-29 05:39:54 发布
网友
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake', 'iguana', 'tiger', 'eagle'] vowel=[] for vowel in words: if vowel [0]=='a,e': words.append(vowel) print (words)
我的代码不对,它会打印出原始列表中的所有单词。
下面是一个单行本的答案,包含列表理解:
>>> print [w for w in words if w[0] in 'aeiou'] ['apple', 'orange', 'otter', 'iguana', 'eagle']
好的python读起来几乎像自然语言:
vowel = 'a', 'e', 'i', 'o', 'u' words = 'apple', 'orange', 'pear', 'milk', 'otter', 'snake', 'iguana', 'tiger', 'eagle' print [w for w in words if w.startswith(vowel)]
w[0]解决方案的问题在于它不能处理空单词(在这个特定的示例中无关紧要,但在分析用户输入等实际任务中很重要)。
w[0]
words = ['apple', 'orange', 'pear', 'milk', 'otter', 'snake','iguana','tiger','eagle'] for word in words: if word[0] in 'aeiou': print(word)
你也可以使用这样的列表理解
words_starting_with_vowel = [word for word in words if word[0] in 'aeiou']
下面是一个单行本的答案,包含列表理解:
好的python读起来几乎像自然语言:
w[0]
解决方案的问题在于它不能处理空单词(在这个特定的示例中无关紧要,但在分析用户输入等实际任务中很重要)。你也可以使用这样的列表理解
相关问题 更多 >
编程相关推荐