我有一个嵌套列表:
l = [['GILTI', 'was', 'intended', 'to','to', 'stifle', 'multinationals'. 'was'],
['like' ,'technology', 'and', 'and','pharmaceutical', 'companies', 'like']]
如何在不使用set或其他类似操作的情况下检测两个连续的元素并删除一个?这应该是所需的输出:
l = [['GILTI', 'was', 'intended','to', 'stifle', 'multinationals'. 'was'],
['like' ,'technology', 'and','pharmaceutical', 'companies', 'like']]
我尝试像这样使用itertools groupby:
from itertools import groupby
[i[0] for i in groupby(l)]
还有一个命令字典:
from collections import OrderedDict
temp_lis = []
for x in l:
temp_lis.append(list(OrderedDict.fromkeys(x)))
temp_lis
退出:
[['GILTI', 'was', 'intended', 'to', 'stifle', 'multinationals'],
['like', 'technology', 'and', 'pharmaceutical', 'companies']]
第二种解决方案可能效果很好。但是,这是错误的,因为它正在删除不连续的重复元素(例如was和like)。如何获得上面的所需输出?
答案 0 :(得分:2)
您可以像这样使用groupby
:
[[k for k, g in groupby(x)] for x in l]
如果有多个重复的连续元素,则将保留一个。
如果您需要完全删除重复的连续元素,请使用:
[[k for k, g in groupby(x) if len(list(g)) == 1] for x in l]
示例:
from itertools import groupby
l = [['GILTI', 'was', 'intended', 'to','to', 'stifle', 'multinationals', 'was'],
['like' ,'technology', 'and', 'and','pharmaceutical', 'companies', 'like']]
print([[k for k, g in groupby(x)] for x in l])
# [['GILTI', 'was', 'intended', 'to', 'stifle', 'multinationals', 'was'],
# ['like', 'technology', 'and', 'pharmaceutical', 'companies', 'like']]
答案 1 :(得分:2)
自定义生成器解决方案:
def deduped(seq):
first = True
for el in seq:
if first or el != prev:
yield el
prev = el
first = False
[list(deduped(seq)) for seq in l]
# => [['GILTI', 'was', 'intended', 'to', 'stifle', 'multinationals', 'was'],
# ['like', 'technology', 'and', 'pharmaceutical', 'companies', 'like']]
编辑:先前的版本无法将None
作为第一个元素。
答案 2 :(得分:1)
例如。
l = [['GILTI', 'was', 'intended','to', 'stifle', 'multinationals','was'],
['like' ,'technology', 'and','pharmaceutical', 'companies', 'like']]
result = []
for sublist in l:
new_list = []
for index,x in enumerate(sublist):
#validate current and next element of list is same
if len(sublist)-1 >= index+1 and x == sublist[index+1]:
continue
#append none consecutive into new list
new_list.append(x)
#append list into result list
result.append(new_list)
print(result)
O / P:
[['GILTI', 'was', 'intended', 'to', 'stifle', 'multinationals', 'was'],
['like', 'technology', 'and', 'pharmaceutical', 'companies', 'like']]