【问题标题】:Merge items in list if they're alike and next to each other如果它们相似且彼此相邻,则合并列表中的项目
【发布时间】:2017-11-27 12:54:15
【问题描述】:

假设我有两个列表:

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],我如何将所有这些组合成一个列表中的一项?

【问题讨论】:

    标签: python python-2.7 list


    【解决方案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)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 2015-09-11
      • 2016-03-20
      • 2017-10-22
      • 1970-01-01
      • 2018-04-15
      相关资源
      最近更新 更多