I have a list that contains multiple sublists, each filled with random integers. I'm trying to figure out a way to check which elements from the first sublist are present in every sublist, here's what I came up with so far:
for element in sublist1:
x = 1
for i in range(len(list_of_sublists)-1):
if element in list_of_sublists[i]:
x = x 1
elif element not in list_of_sublists[i]:
x = x - 1
if x == len(allDocIDs):
listOfDocumentIDs.append(element)
else:
pass
It seems to work when there are 2 sublists, but once there are 3 or more it seems like the code is ignoring their existence. Is there a simpler (and more functional) way to perform this task?
CodePudding user response:
You can do loop through the first sublist (set
just ensures that every i in the for loop is unique so you don't check a value twice) and check if each value is in every sublist with all
:
a = [[1,2,3,4], [2,2,2,2,1], [3,3,3,3,1], [4,4,4,1,4,4]]
for i in set(a[0]):
print(i, all((i in j for j in a)))
Output:
1 True
2 False
3 False
4 False
Or with list comprehension:
[(i, all((i in j for j in a))) for i in list(set(a[0]))]
Output:
[(1, True), (2, False), (3, False), (4, False)]
CodePudding user response:
If the element is in the first sublist and in all the other sublists, then it's in all sublists. So your questions is equivalent to asking which items are in all lists. You can do this efficiently with sets by taking the intersection of all the sublists:
a = [[1,2,3,4], [2,2,4,2,1], [3,4,3,3,1], [4,4,4,1,4,4]]
set.intersection(*[set(l) for l in a])
# {1, 4}
This assumes you don't care about duplicates in the first sublist. If you do care about duplicates in the first sublist, you can take the intersection of the rest of the sublist and then use a list comprehension to filter the elements from the first:
a = [[1, 2, 3, 4, 1], [2,2,4,2,1, 6], [3,4,3,3,1, 6], [4,4,4,1,4,4, 6]]
elements = set.intersection(*[set(l) for l in a[1:]])
[n for n in a[0] if n in elements]
# [1, 4, 1]