[英]Find common sequence of elements in list of lists
我有包含 ID 的列表列表如下 -
[[45, 41, 20, 25, 78],
[54, 12, 45, 36, 59],
[45, 12, 45, 41, 88],
[74, 85, 41, 20, 25],
[54, 45, 36, 59],
[74, 20, 25]]
問題 1:我需要在一個列表中具有相同前綴(以相同數字開頭的列表)的所有列表。 所需 output
[[45, 41, 20, 25, 78],
[45, 12, 45, 41, 88]]
[[54, 12, 45, 36, 59],
[54, 45, 36, 59]]
[[74, 85, 41, 20, 25],
[74, 20, 25]]
問題2:稍后在各個子列表中找到共同的元素。 例如:
[[45, 41, 20, 25, 78],
[45, 12, 45, 41, 88]]
在此列表中,常見元素是 [45,41]
最終所需的 output:
[[45, 41],
[54, 45, 36, 59],
[74, 20, 25]]
您可以使用itertools.groupby
解決問題 1:
from itertools import groupby
orig_list = [[45, 41, 20, 25, 78],
[54, 12, 45, 36, 59],
[45, 12, 45, 41, 88],
[74, 85, 41, 20, 25],
[54, 45, 36, 59],
[74, 20, 25]]
sorted_list = sorted(orig_list, key=lambda l: l[0])
list1 = [list(g) for _, g in groupby(sorted_list, lambda l:l [0])]
Output:
[[[45, 41, 20, 25, 78], [45, 12, 45, 41, 88]],
[[54, 12, 45, 36, 59], [54, 45, 36, 59]],
[[74, 85, 41, 20, 25], [74, 20, 25]]]
對於問題 2,您可以使用set intersection ; 但是,它不會保留順序:
[list(set.intersection(*[set(s) for s in sublists])) for sublists in list1]
Output:
[[41, 45], [59, 36, 45, 54], [25, 74, 20]]
如果你想保留順序並且總是有 2 個子列表,你可以試試這個:
[[x for x in sublist[0] if x in sublist[1]] for sublist in list1]
Output:
[[45, 41], [54, 45, 36, 59], [74, 20, 25]]
如果可能有其他數量的子列表(超過 2 個或只有 1 個),您可以像這樣調整它:
[[x for x in sublist[0] if all([x in s for s in sublist[1:]])] for sublist in pre_list]
我認為這是您的解決方案
list1 = [[45, 41, 20, 25, 78],[54, 12, 45, 36, 59],[45, 12, 45, 41, 88],[74, 85, 41, 20, 25],[54, 45, 36, 59],[74, 20, 25]]
converted_list = []
i=0
while i <= (len(list1)/2)+1:
a = list1.pop(0)
print(a)
for j in list1:
if j[0]==a[0]:
b = list1.pop(list1.index(j))
converted_list.append([a,b])
break
i+=1
print(converted_list)
final_list = []
for i in converted_list:
common_list = []
for j in i[0]:
if j in i[1]:
common_list.append(j)
final_list.append(common_list)
print(final_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.