Paul Buga Paul Buga - 6 months ago 8
Python Question

How to determine how many unique other items an integer has been with in a list of lists of lists?

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]]]


Given the integer 1, I would like some way to make a function that will return

[2, 3, 4, 6]


My current method is:

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))


I know this is a naive algorithm. What is a better, more pythonic way to do it?

Answer

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}
Comments