I guess I'm kinda addicted to List comprehensions, and could not resist to give them a try at this problem.
Ergo:
ml1 = [[0, 0, 1], [100, 0, 2], [200, 0, 3], [300, 0, 4], [0, 200, 9], [100, 200, 10], [200, 200, 11], [300, 200, 12], [0, 400, 17], [100, 400, 18], [200, 400, 19], [300, 400, 20]]
ss = 4 ## SectioonSize
print;print 1.0, ml1
if len(ml1)%ss:
print;print("NOTE: List length not a multiple of", ss)
## continueing anyway
ml2 = [ (ml1[i*ss:(i+1)*ss]) for i in range(int(len(ml1)/ss)) ] ## Split source list into sections of 4 entries.
ml3 = [ sl[i][0:ss-2] + [sl[len(sl)-i-1][2]] for sl in ml2 for i in range(len(sl)) ] ## process the sections.
print;print 2.0, ml3
Output:
1.0 [[0, 0, 1], [100, 0, 2], [200, 0, 3], [300, 0, 4], [0, 200, 9], [100, 200, 10], [200, 200, 11], [300, 200, 12], [0, 400, 17], [100, 400, 18], [200, 400, 19], [300, 400, 20]]
2.0 [[0, 0, 4], [100, 0, 3], [200, 0, 2], [300, 0, 1], [0, 200, 12], [100, 200, 11], [200, 200, 10], [300, 200, 9], [0, 400, 20], [100, 400, 19], [200, 400, 18], [300, 400, 17]]
(
General code readability was not a high priority in this case)
(
code edit: renamed s1 var to ss)
---
General working:
(
presuming one knowns general basics of list-comprehensions.)
As the required reversal is limited to sections of 4 main-list entries we first split the source data into sections of 4. So those sections can be processed independent of the other data.
This is done by dividing the total length of the list by the intended section length, and than storing those sections as separate sub-lists.
ml2 = [ i for i in range(int(len(ml1)/ss)) ] ## => [1,2,3] :: walk trough the number of sets of 4.
ml2 = [ ( i*ss , (i+1)*ss ) for i in range(int(len(ml1)/ss)) ] ## => [(0, 4), (4, 8), (8, 12)] :: list capture parts per section.
ml2 = [ ( ml1[ i*ss : (i+1)*ss ] ) for i in range(int(len(ml1)/ss)) ] ## => [ ml1[0:4], ml1[4:8], ...] :: final section split.
Now the sections can be processed separately.
First we split/target the main list section parts with the
for sl in ml2
part. (sl=SubList).
Than we set up the sl part targeting with
for i in range(len(sl)
Now we can swap the last element in the section parts (
done per main-list section).
sl[i][0:s1-2]
takes care of capturing the leading elements, to which we add the reversed last element
[sl[len(sl)-i-1][2]]
(
note: this last part is not making use of the ss var, although it probably could/should, without using ss using list[:-1] an list[-1] calls would make more sense here (probably/untested).)
ml3 = [ i for sl in ml2 for i in range(len(sl)) ] ## => [0, 1, 2, 3, 0, 1, 2, 3, ...]
ml3 = [ len(sl)-i-1 for sl in ml2 for i in range(len(sl)) ] ## => [3, 2, 1, 0, 3, 2, 1, 0, ...]