【问题标题】:Find the longest unique strings from list of strings python从字符串列表python中查找最长的唯一字符串
【发布时间】:2018-10-25 10:21:43
【问题描述】:

我有一个字符串列表

这些字符串由将包含在其他字符串中的字符串组成

以及最长迭代中唯一的字符串

例如在我的列表中可能有以下

4|131
4|201
4|131|2644
4|131|2644|547
4|131|2644|1482
2644

我希望能够将其减少到最长的唯一实体

4|201
4|131|2644|547
4|131|2644|1482
2644

我想知道python中是否有一个标准函数可以完成这个过程

【问题讨论】:

标签: python string longest-substring


【解决方案1】:

不,Python 中没有标准函数。

【讨论】:

    【解决方案2】:

    没有单一的功能,但很容易自己构建一个:

    lst = sorted(lst)
    longests = [lst[0]]
    for item in lst:
        if item.startswith(longests[-1]):
            longests[-1] = item
        else:
            longests.append(item)
    
    print(longests)
    

    另一种方法:

    from operator import itemgetter
    from itertools import groupby
    
    class adjacent:
        def __init__(self, func, init=None):
            self.func = func
            self.last = init
    
        def key(self, value):
            if not self.func(self.last, value):
                self.last = value
            return self.last
    
    slst = sorted(lst, reverse=True)
    groups = groupby(slst, adjacent(str.startswith, "").key)
    longests = map(itemgetter(0), groups)
    
    print(list(longests))
    

    请注意,上述实现将“4|1”视为“4|131”的前缀,因为它使用字符串匹配。如果你只想匹配管道之间的整个字符串,你只需要先在管道上拆分,然后replace with a startswith for list

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-11
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      相关资源
      最近更新 更多