此代码应在列表中打印唯一的元音?但是为什么要打印重复的元音?

时间:2018-07-30 16:57:38

标签: python python-3.x

v = ['a','e','i','o','u']
word ="Milliwaysaaa"
found = []
for i in word:
    if i in v:
        if i not in found:
            print(i) 

这应该只打印独特元音,但是会全部打印。为什么?

4 个答案:

答案 0 :(得分:2)

您可以使用set()操作,这将打印出元音和单词共有的元素:

vowels = ['a','e','i','o','u']
word ="Milliwaysaaa"

print(set(vowels) & set(word))

打印:

{'i', 'a'}

答案 1 :(得分:0)

遇到新的元音时,您需要更新found。 添加该行:

v = ['a','e','i','o','u']
word ="Milliwaysaaa"
found = []
for i in word:
    if i in v:
        if i not in found:
            print(i)
            found.append(i)

答案 2 :(得分:0)

您的问题是您什么时候都没有在found列表中添加任何内容,这意味着它始终为空。

尝试在打印语句后添加found.append(i)

此外,这是一种更简洁的方法来实现您想要的目标:

v = ['a', 'e', 'i', 'o', 'u']
word = "Milliwaysaaa"

found = set(filter(lambda i: i in v, word))

print(found)

输出:

{'a', 'i'}

答案 3 :(得分:0)

from collections import Counter
v = ['a','e','i','o','u']
word ="Milliwaysaaa"

d=dict(Counter(word))
found=[key for key in d.keys() if key in v]

#['a', 'i']