Setup
Given a list of lists of lists, such as the one below:
lll = []
for _ in range(5):
ll = [random.sample(range(1, 20), 5),
random.sample(range(1, 20), 5),
random.sample(range(1, 20), 5)]
lll.append(ll)
Which might give:
[[[1, 15, 12], [8, 5, 13], [1, 9, 12]],
[[4, 1, 19], [11, 18, 3], [8, 14, 6]],
[[17, 8, 4], [1, 16, 3], [19, 13, 11]]]
End Goal
I want to get the lowest index that an element appears, and return this output in the form of a dictionary, e.g.:
{0: {1, 17, 19, 4, 8, 11}, 1: {5, 9, 13, 14, 15, 16, 18}, 2: {3, 12, 6}}
For example, in lll above, 8 appears in 3 sublists. But it's lowest position in a single sub-list is at 0, which is why it's in the final dictionary at key 0.
Constraint
I must iterate over lll (my use-case assumes that I do not know the full lll). Therefore the traversal_dct will build up over time. The lll seen above is dummy data for demonstration purposes.
Working Solution
This current approach works, but I'm sure it could be more efficient.
traversal_dct = {}
for ll in lll:
llT = [*map(list, zip(*ll))]
for i,xs in enumerate(llT):
if i not in traversal_dct.keys():
traversal_dct[i] = set()
traversal_dct[i] = traversal_dct[i].union(set(xs))
for i1,key1 in enumerate(traversal_dct.keys()):
for i2,key2 in enumerate(traversal_dct.keys()):
if i2 > i1:
traversal_dct[i2] = traversal_dct[i2] - traversal_dct[i1]