python - Iterate with last element repeated as first in next iteration -
i have list objects looks like:
oldlist=[a,b,c,d,e,f,g,h,i,j,...] what need create new list nested list items this:
newlist=[[a,b,c,d],[d,e,f,g],[g,h,i,j]...] or spoken - last element previous nested first element in next new nested list.
one of ways of doing is
>>> l = ['a','b','c','d','e','f','g','h','i','j'] >>> [l[i:i+4] in range(0,len(l),3)] [['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j'], ['j']] here :
l[i:i+4]implies print chunk of 4 values starting positionirange(0,len(l),3)implies traverse length of list taking 3 jumps
so basic working of that, taking chunk of 3 elements list, modifying slice length includes additional element. in way, can have list of 4 elements.
small note - initialization oldlist=[a,b,c,d,e,f,g,h,i,j,...] invalid unless a,b,c,d,etc defined. perhaps looking oldlist = ['a','b','c','d','e','f','g','h','i','j']
alternatively, if wanted solution split even sized chunks only, try code :-
>>> [l[i:i+4] in range(0,len(l)-len(l)%4,3)] [['a', 'b', 'c', 'd'], ['d', 'e', 'f', 'g'], ['g', 'h', 'i', 'j']]
Comments
Post a Comment