【问题标题】:Make compound strings in list based on list根据列表在列表中制作复合字符串
【发布时间】:2020-09-08 18:55:17
【问题描述】:

我有以下列表:

lst_a=['a1 b1 c1','a2 b2','a3 b3 c3 d3']
lst_b=['a1','b1','c1','d','e','a3','b3','c3','d3','f','a2', 'b2']

lst_b 中的输出将基于 lst_a 生成复合字符串,如下所示:

result=['a1 b1 c1','d','e','a3 b3 c3 d3','f','a2 b2']

如何根据 lst_a 使列表 b 将独立项更改为复合项?

【问题讨论】:

  • 它们不是列表。
  • 我有点困惑你如何从第一个 sn-p 到第二个。看起来您想要来自lst_a 的分组,以及来自lst_b 的排序,然后还有来自lst_b 的任何剩余元素?或者如果存在的话,只需使用lst_b 并按第二个字符分组就足够了吗?
  • lst_a 仅包含每个项目的复合字符串,而 list_b 包含所有项目作为单个字符串。然后,结果具有 lst_a 中存在的项目的复合字符串,如果它是单个项目而不是复合项目,还包括 lst_b 中的项目。

标签: python python-3.x list sorting


【解决方案1】:

遍历lst_b,并连接其元素,直到结果不再是lst_a元素的前缀。

lst_a=['a1 b1 c1','a2 b2','a3 b3 c3 d3']
lst_b=['a1','b1','c1','d','e','a3','b3','c3','d3','f','a2', 'b2']

r = []
current = lst_b[0]
for w in lst_b[1:]:
  new_current = ' '.join([current, w])
  if new_current in (v[:len(new_current)] for v in lst_a):
    current = new_current
  else:
    r.append(current)
    current = w
r.append(current)

print(r)

输出: ['a1 b1 c1', 'd', 'e', 'a3 b3 c3 d3', 'f', 'a2 b2']

备注:由于您仅给出了 lst_alst_b 的这个非常特殊的示例,因此我无法说出该算法是否符合您将问题推广到其他人的期望例子。

【讨论】:

    【解决方案2】:

    试试这个,有点难看,但应该可以。

    lst_a=['a1 b1 c1','a2 b2','a3 b3 c3 d3']
    lst_b=['a1','b1','c1','d','e','a3','b3','c3','d3','f','a2', 'b2']
    
    r = []
    seps = 0
    for i, ele in enumerate(lst_b):
        if seps == 0:
            f = [i for i in lst_a if i.startswith(ele)]
            if f:
                f = f[0]
                seps = f.count(" ")
                if " ".join(lst_b[i:i+seps+1]) == f:
                    r.append(f)
                    lst_a.remove(f)
                else:
                    r.append(ele)
            else:
                r.append(ele)
        else:
            seps -= 1
    
        
    # Out[68]: ['a1 b1 c1', 'd', 'e', 'a3 b3 c3 d3', 'f', 'a2 b2']
    

    【讨论】:

    • 感谢您的回答@Andreas。该解决方案不起作用,因为 lst_a 和 lst_b 中的顺序很重要。例如,如果您将 lst_a 更改为 lst_a=['a1 c1','a2 b2','a3 b3 c3 d3'],则不会发现不应考虑 a1c1,因为在 lst_b 中有 'a1','b1','c1'
    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多