繁体   English   中英

如果字符串不包含 Python 中的某些字符,我如何从列表中删除它

[英]How do i remove a string from a list if it DOES NOT contain certain characters in Python

我正在研究列表过滤器。 这就是我所走的。 我想删除每个不包含HLC字符串。 到目前为止,这是我的尝试

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:

使用这个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

为了清楚起见,您可以使用一个函数

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)]

暂无
暂无

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

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