如果列表中不包含Python中的特定字符,如何从列表中删除该字符串
我正在做一个列表过滤器。这就是我所走的路了。我想删除所有不包含如果列表中不包含Python中的特定字符,如何从列表中删除该字符串,python,string,list,filter,character,Python,String,List,Filter,Character,我正在做一个列表过滤器。这就是我所走的路了。我想删除所有不包含H、L或C的字符串。到目前为止,这是我的尝试 input_list = input("Enter The Results(leave a space after each one):").split(' ') for i in input_list: if 'H'not in i or 'L' not in i or 'C' not in i: 为了清楚起见,您可以使用函数 def contains_invalid_cha
H
、L
或C
的字符串。到目前为止,这是我的尝试
input_list = input("Enter The Results(leave a space after each one):").split(' ')
for i in input_list:
if 'H'not in i or 'L' not in i or 'C' not in i:
为了清楚起见,您可以使用函数
def contains_invalid_character(my_string):
return 'H' in my_string or 'L' in my_string or 'C' in my_string
# To be more pythonic, you can use the following
# return next((True for letter in ("H", "L", "C") if letter in my_string), False)
results = []
for i in input_list:
if not contains_invalid_character(i):
results.append(i)
# Or to be more pythonic
# results = [i for i in input_list if not contains_invalid_character(i)]
使用这个pythonic代码
input_list = input("Enter The Results(leave a space after each one):").split(' ') # this is the input source
after_removed = [a for a in input_list if ('H' not in a and 'L' not in a and 'C' not in a)] # this is the after removed 'H', 'L', and 'C' from the input_list
使用列表理解,可以使python变得更简单、更快
如果你不相信,就自己试试看:D你想用和,而不是或,用于你的情况。