【问题标题】:How to delete substring from a list and have a full string of it present in list?如何从列表中删除子字符串并在列表中显示完整的字符串?
【发布时间】:2018-11-30 11:27:32
【问题描述】:

我有一个 python 列表,其中包含完整字符串的许多子字符串,包括完整字符串。有人可以帮我从列表中删除所有子字符串并且只有完整的字符串。

lists = ['ab','bcd','cd','abcd','ef']

对于上述输入,我希望输出为:

lists = ['abcd','ef']

请注意,不要考虑此示例中的字符串长度,因为我的实际列表项长度波动很大。

【问题讨论】:

    标签: python-3.x substring


    【解决方案1】:

    这不是python代码,而是我的算法。希望有效

    让我们有 2 个数组,array1 用于输入,array2 用于结果

    1. 在数组中查找最长的元素
    2. 对于array1 中的每个元素,检查较短的元素:
      • 如果包含 [重复] -> 删除
      • 如果不保留
      • 在新的array2 中添加这个长元素并 从array1 中删除
    3. 对于那些保留的元素
      • 再次执行第 2 步,直到完成
      • 如果array1 中只剩下 1 个元素 .只需将其添加到array2

    【讨论】:

      【解决方案2】:
      import copy
      listA = ['abc','bcd','abcd', 'ef', 'eef']
      listB=copy.deepcopy(listA) # create 2nd copy of main list 
      new_list=[]
      global longest_str
      longest_str=max(listA, key=len)
      l_len=len(listA)
      while l_len>0:
          for l in listB:
              if l in longest_str and len(l)<len(longest_str):
                  listA.remove(l)  # remove the sub-string
              if longest_str == l:  
                  new_list.append(l) #append longest string in new_list
                  listA.remove(l) #remove from the main list 
          l_len=len(listA)
          if l_len>0:
              longest_str=max(listA, key=len)
      
      print(new_list)
      

      【讨论】:

        猜你喜欢
        • 2021-06-24
        • 2015-04-23
        • 2018-06-29
        • 1970-01-01
        • 2015-10-25
        • 2016-04-03
        • 1970-01-01
        相关资源
        最近更新 更多