简体   繁体   English

迭代if函数

[英]Iterative if function

I am currently working on a python script which will take a string, convert it to a list, and then remove all of the vowels. 我目前正在研究一个python脚本,该脚本将使用字符串,将其转换为列表,然后删除所有元音。 It then prints out the final result as a string. 然后将最终结果打印为字符串。 However, the iterative function I am using is outputting every result, whether it is a vowel or not. 但是,我正在使用的迭代函数将输出每个结果,无论它是否是元音。 I have tried reversing and only keeping the consonants, but to no avail. 我试过反转,只保留辅音,但无济于事。 Below is the code I was using. 下面是我正在使用的代码。

string = input("#: ")
new_list = []

for x in list(string):
    if [x.lower() == y for y in list("aeiou")]:
        global new_list
        new_list.append(x)

print(''.join(new_list))

Any insight would be appreciated. 任何见识将不胜感激。

This line: 这行:

if [x.lower() == y for y in list("aeiou")]

creates a list with five elements (each of which is True or False ). 创建一个包含五个元素的列表(每个元素为TrueFalse )。
For instance, if x is 'e' , it will create the list 例如,如果x'e' ,它将创建列表

[False, True, False, False, False]

If x is not a vowel, it will create the list 如果x不是元音,它将创建列表

[False, False, False, False, False]

Any non-empty list is true, so the if condition is satisfied. 任何非空列表都为true,因此满足if条件。


What you mean to ask is "does x.lower() equals y for any y in my list of vowels?", which is this: 您要问的意思是“对于我的元音列表中的任何yx.lower()等于y吗?”,这是:

if any(x.lower()==y for y in list("aeiou")):

or more succinctly: 或更简洁地:

if x.lower() in "aeiou":

If you want to check if a letter is not a vowel, it would be this: 如果要检查字母是否不是元音,则为:

if x.lower() not in "aeiou":

I'm not entirely sure what did you try to do there but this does it... 我不完全确定您尝试在那做什么,但这可以做到...

string = input("#: ")
print(''.join([x for x in string if x.lower() not in "aeiou"]))

#: Hello there!
Hll thr!

An even more efficient approach would be: 甚至更有效的方法是:

print(input("#: ").translate(str.maketrans("","","aeiou")))

one liner show off: 一支衬板炫耀:

string = input("#: ")
print(''.join(filter(lambda x: x.lower() in 'aeiou', string)))

References 参考文献

[1] https://docs.python.org/2/library/functions.html#filter [1] https://docs.python.org/2/library/functions.html#filter

[2] http://www.diveintopython.net/power_of_introspection/lambda_functions.html [2] http://www.diveintopython.net/power_of_introspection/lambda_functions.html

First thing, a string is an iterator just like a list so no need to typecast a string to list. 首先,字符串是一个迭代器,就像列表一样,因此无需将字符串强制转换为列表。

s = "your_string_goes_here".lower()

s = s.replace('a', '')
s = s.replace('i', '')
s = s.replace('e', '')
s = s.replace('o', '')
s = s.replace('u', '')
print s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM