【发布时间】: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