合并列表中的项目,如果它们相似并且彼此相邻

时间:2017-11-27 04:15:54

标签: python python-2.7 list

假设我有两个列表:

list_one = ["Alex", "Alex", "John", "Alex", "John", "John"]
list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"]

我希望在列表一中将相同的项目合并在一起(将此列表称为三个)

list_one = ["Alex", "Alex", "John", "Alex", "John", "John"]
list_three = ["Alex", "John", "Alex", "John"]

并列出两个转到列表四,它遵循合并第一个列表中的项目的“模式”:

list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"]
list_four = ["Hi Are you there?", "Hello Alex!", "How are you John?", "I am good Alex How about yourself?"]

我该怎么办?我发现了这个:Remove adjacent duplicate elements from a list,但它没有处理多个列表,我不想从第二个列表中删除项目。

编辑:我找到了一个帖子,我可以在列表中获取项目的所有实例,他们使用的代码是:

def all_indices(value, qlist):
indices = []
idx = -1
while True:
    try:
        idx = qlist.index(value, idx+1)
        indices.append(idx)
    except ValueError:
        break
return indices

现在如果我为我的代码执行此操作,我会得到两个列表:

Alex = [0,1,3]
John = [2,4,5]

但是,如何编写一个将list_two [0]和list_two [1]组合在一起的函数?或者如果Alex = [0,1,2,3,4,5],我怎么能将所有这些组合成一个列表中的一个项呢?

1 个答案:

答案 0 :(得分:1)

另一个groupby解决方案:

from itertools import groupby

list_one = ["Alex", "Alex", "John", "Alex", "John", "John"]
list_two = ["Hi", "Are you there?", "Hello Alex!", "How are you John?", "I am good Alex", "How about yourself?"]

l2iter = iter(list_two)
list_three, list_four = zip(*((key, ' '.join(next(l2iter) for whatever in grp)) for key, grp in groupby(list_one)))