【问题标题】:python - filter list by substring of second listpython - 按第二个列表的子字符串过滤列表
【发布时间】:2020-08-28 02:03:33
【问题描述】:

我正在尝试根据 list2 中子字符串的出现来删除同一索引的 list1 中的项目。

List1 = ["1", "2", "3", "4"]

List2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]

结果应该是:

List1 = ["3", "4"]

List2 = ["OtherValue1", "Othervalue2"]

从逻辑上看:

检查 List2 中的元素是否以/包含子字符串“Remove”开头,如果为真:删除此条目和 List1 中具有相同索引的条目。

我搜索了很多主题和问题,但通常他们希望将 2 个列表与(部分)相同的条目进行比较并相应地过滤它们。从逻辑的角度来看,我可以想到很多方法来执行它,不幸的是,我缺乏将它放在一起的 python 语法知识(一旦我看到正确的代码,我很可能会说“当然,简单,有意义"-.-")

提前感谢您的帮助, 托比

【问题讨论】:

    标签: python string list indexing filter


    【解决方案1】:

    您可以使用 zip() 将两个列表压缩成一个元组列表,然后对其进行迭代。

    >>> List1 = ["1", "2", "3", "4"]
    >>> List2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
    
    >>> result1 = []
    >>> result2 = []
    >>> for x,y in zip(List1,List2):
    ...     if "Remove" not in y:
    ...         result1.append(x)
    ...         result2.append(y)
    >>> result1
    ['3', '4']
    >>> result2
    ["OtherValue1", "Othervalue2"]
    

    【讨论】:

      【解决方案2】:

      假设条件保持不变。应用相同的逻辑以便更好地理解。只需将剩余元素分配给同一个列表(这里假设 Remove 字符串在这些列表中的 OtherValue 之前)。

      list1 = ["1", "2", "3", "4"]
      list2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
      
      for i,j in zip(list1, list2):
          if "Remove" in j:
              list1 = list1[1:]
              list2 = list2[1:]
      
      print(list1)
      print(list2)
      

      【讨论】:

        【解决方案3】:

        你可以试试这个

        def RemoveItems(List1, List2):
            List1 = ["1", "2", "3", "4"]
            List2 = ["Remove1", "Remove2", "OtherValue1", "Othervalue2"]
            index = []
        
            for item in List2:
                if item.startswith('Remove'):
                    index.append(List2.index(item))
        
            index.reverse()
        
            for item in index:
                del List1[item]
                del List2[item]
        
            return (List1, List2)
        
        List1, List2 = RemoveItems(List1, List2)
        
        print("List1 : ", List1)
        print("List2 : ", List2)
        

        【讨论】:

          猜你喜欢
          • 2021-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-03
          • 2017-04-23
          • 2018-02-12
          相关资源
          最近更新 更多