【问题标题】:How do i remove a string from a list if it DOES NOT contain certain characters in Python如果它不包含Python中的某些字符,我如何从列表中删除一个字符串
【发布时间】:2020-03-25 03:08:47
【问题描述】:

我正在研究一个列表过滤器。这是我去过的地方。我想删除所有不包含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:

【问题讨论】:

  • 您想使用 and 而不是 or,对于您的情况。

标签: python string list filter character


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-18
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多