'Dictionary/list/tuple comprehension from 3 lists

Say I have the following 3 lists:

x = ['a', 'a', 'b', 'b']
y = ['y1', 'y2', 'y3', 'y4']
z = ['p', 'p', 'p', 'p']

I am trying to get the output to:

[('a',['y1', 'y2'], ['p', 'p']),('b',['y3', 'y4'], ['p', 'p'])]

x repeats at a fixed known length (here known length is 2, i.e. next in the sequence would be c,c). x % known length is not necessarily 0. z won't always have the same items.

I have tried with defaultdict and many versions of comprehension but can't seem to crack it. The lists I will be working on are actually much larger, therefore for loops take a really long time. So I need something with high performance.



Solution 1:[1]

This list comprehension seems to do the trick:

data = [(x[i], [y[i], y[i + 1]], [z[i], z[i + 1]]) for i in range(0, len(x), 2)]
print(data)

Output

[('a', ['y1', 'y2'], ['p', 'p']), ('b', ['y3', 'y4'], ['p', 'p'])]

Note: I assumed x to always have the same values ??pairwise.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cubix48