I've got a list of lists, with integers in it, like this:
[[[1, 2, 3], [4, 5, 6, 7]], [[3, 7, 5], [1, 2, 4, 6]]]
[2, 3, 4, 6]
bigList = [[[1, 2, 3], [4, 5, 6, 7]], [[3, 7, 5], [1, 2, 4, 6]]]
hasBeenWith = []
integer = 1
for medList in bigList:
for smallList in medList:
if integer in smallList:
hasBeenWith = hasBeenWith + list(set(smallList) - set(hasBeenWith))
This is a bit shorter, and still pretty readable. Since you only care about the bottom level lists, it would be more readable IMO if you had a function that flattened the nested list structure down to a single iterable of lists (basically what all the chain
's and list comprehensions are doing. Then you could just have a single list comprehension that iterates through the flattened structure.
from itertools import chain
num = 1
biglist = [[[1, 2, 3], [4, 5, 6, 7]], [[3, 7, 5], [1, 2, 4, 6]]]
been_with = set(chain(*[x for x in chain(*biglist) if num in x])) - {num}