I want to go from a data structure like:
[[0, 12, 25, 45, 65, 100],
[0, 0, 0, 255, 255, 255],
[0, 0, 255, 255, 0, 0],
[255, 255, 0, 0, 0, 0]]
to:
[[0, 12, 12, 25, 25, 45, 45, 65, 65, 100],
[0, 0, 0, 0, 0, 255, 255, 255, 255, 255],
[0, 0, 0, 255, 255, 255, 255, 0, 0, 0],
[255, 255, 255, 0, 0, 0, 0, 0, 0, 0]]
(All columns except for the first and the last one are repeated).
I have the following list comprehension that works:
[[l[0]] + [x for sl in [[i, i] for i in l[1:-1]] for x in sl] + [l[-1]] for l in list_of_lists]
but I was wondering if there is a more elegant and more readable way to write this.
I think you should also consider that “more readable” doesn’t necessarily mean the same as “is it possible to cram this into one line?”. It can often mean more explicit and straight-forward iterative code. Perhaps you might find this function more readable:
Then your code becomes very simple: