代码之家  ›  专栏  ›  技术社区  ›  Aliaksei Laurynovich

基于另一个列表中子字符串的顺序排序列表

  •  3
  • Aliaksei Laurynovich  · 技术社区  · 6 年前

    我有两个字符串列表。

    list_one = ["c11", "a78", "67b"]
    list_two = ["a", "b", "c"]
    

    最短的分类方法是什么 list_one 使用字符串 list_two 以获得以下输出?

    ["a78", "67b", "c11"]
    

    编辑1: 有一个类似的问题 Sorting list based on values from another list? ,但在这个问题上,他已经有了结果字符串所需的索引列表,而这里只有子字符串列表。

    编辑2: 由于以上列表的示例可能不完全具有代表性,因此我添加了另一个案例。

    一个是 ["1.cde.png", "1.abc.png", "1.bcd.png"] 列表二是 ["abc", "bcd", "cde"] . 输出应该是 [ "1.abc.png", "1.bcd.png", "1.cde.png"]

    例如,如果列表一比列表二短,它应该仍然有效:

    一个是 ["1.cde.png", "1.abc.png"] 列表二是 [“ABC”,“BCD”,“CDE”] 输出应该是 [ "1.abc.png", "1.cde.png"]

    4 回复  |  直到 6 年前
        1
  •  4
  •   blhsing    6 年前
    key = {next((s for s in list_one if v in s), None): i for i, v in enumerate(list_two)}
    print(sorted(list_one, key=key.get))
    

    这将输出:

    ['a78', '67b', 'c11']
    
        2
  •  1
  •   khelili miliana    6 年前

    试试这个

    list_one = ["c11", "a78", "67b"]
    list_two = ["a", "b", "c"]
    
    [x for y in list_two for x in list_one if y in x]
    

    输出:

    ["a78", "67b", "c11"]
    
        3
  •  1
  •   tobias_k    6 年前

    假设每个项目 list_one 正好包含来自 list_two ,并且您知道这些字符的类别,例如字母,您可以使用 regex 并构建一个将字符映射到元素的字典。然后,为每个字符查找正确的元素。

    >>> list_one = ["c11", "a78", "67b"]
    >>> list_two = ["a", "b", "c"]
    >>> d = {re.search("[a-z]", s).group(): s for s in list_one}
    >>> list(map(d.get, list_two))
    ['a78', '67b', 'c11']
    >>> [d[c] for c in list_two]
    ['a78', '67b', 'c11']
    

    除了到目前为止发布的其他方法,它们看起来都是o(n),这只是o(n)。

    当然,这种方法可以推广到多个字符,或者第一个字符串的特定位置的字符,但是它总是需要一些模式和关于该模式的知识。例如,对于您最近的示例:

    >>> list_one = ["1.cde.png", "1.abc.png", "1.bcd.png"]
    >>> list_two = ["abc", "cde"]
    >>> d = {re.search("\.(\w+)\.", s).group(1): s for s in list_one}
    >>> d = {s.split(".")[1]: s for s in list_one}  # alternatively without re
    >>> [d[c] for c in list_two if c in d]
    ['1.abc.png', '1.cde.png']
    
        4
  •  -1
  •   Sunitha    6 年前
    >>> sorted(list_one, key=lambda x: [i for i,e in enumerate(list_two) if e in x][0])
    ['a78', '67b', 'c11']