有人可以帮助我理解下面的 for 循环吗? [重复]

问题描述 投票:0回答:1

通过忽略元素中的 a、e、i、o、u,创建字符串“Yellow Yaks like elling and yawning and #yesturday they yodled while eat yuky yams”中所有元素的列表

我写了for循环:

mystring = "Yellow Yaks like yelling and yawning and yesterday they yodled while eating yuky yams"

newlist =[]
mylist=mystring.split()
for word in mylist:
    for letter in ['a','e','i','o','u']:
        if letter in word:
            word =word.replace(letter,'')
    newlist.append(word)
newlist

for循环的输出:

['Yllw',
 'Yks',
 'lk',
 'yllng',
 'nd',
 'ywnng',
 'nd',
 'ystrdy',
 'thy',
 'ydld',
 'whl',
 'tng',
 'yky',
 'yms']

我尝试了以下压缩 for 循环:

mylist=[word.replace(letter,'') for word in mystring.split() for letter in ['a','e','i','o','u'] if letter in word]
mylist

输出:

['Yllow',
 'Yellw',
 'Yks',
 'lik',
 'lke',
 'ylling',
 'yellng',
 'nd',
 'ywning',
 'yawnng',
 'nd',
 'yesterdy',
 'ystrday',
 'thy',
 'yodld',
 'ydled',
 'whil',
 'whle',
 'eting',
 'ating',
 'eatng',
 'yky',
 'yms']

我知道逻辑不正确,但不知道如何解决。您能解释一下需要做什么来解决这个问题以及原因吗?

python list-comprehension
1个回答
0
投票

元音 = 'aeiou' Final_list = [word.translate(str.maketrans('', '', 元音)) for mystring.split() 中的单词] 打印(最终列表)

© www.soinside.com 2019 - 2024. All rights reserved.