Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果列表中不包含Python中的特定字符,如何从列表中删除该字符串_Python_String_List_Filter_Character - Fatal编程技术网

如果列表中不包含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

你想用和,而不是或,用于你的情况。