How To Slice Every Nth Element In Index Using Python?
this might look like a simple question but I could not figure out the solution. Assuming I have this list my_list = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99] I am attempting
Solution 1:
You want to iterate in chunks, with an overlap.
It's a common requirement and in many applications that's called a rolling window. You may use tee
from itertools:
>>> def thinger(iterable, n=3):
... iterators = tee(iterable, n)
... for i, iterator in enumerate(iterators):
... for skip in range(i):
... next(iterator, None)
... return zip(*iterators)
...
>>> list(thinger([1,2,3,4,5,6]))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> list(thinger([1,2,3,4,5,6], n=4))
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]
The zip
actually returns tuples, which is likely be no problem if you're duck-typing, but you can convert them to lists if necessary:
>>> [list(x) for x in thinger([1,2,3], n=2)]
[[1, 2], [2, 3]]
Solution 2:
my_list = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99]
def temp(lst,no):
result = []
for i in range(len(lst)-no+1):
result.append(lst[i:i+no])
return result
print temp(my_list,3)
print temp(my_list,4)
Output
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 11], [9, 11, 22], [11, 22, 33], [22, 33, 44], [33, 44, 55], [44, 55, 66], [55, 66, 77], [66, 77, 88], [77, 88, 99]]
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 11], [8, 9, 11, 22], [9, 11, 22, 33], [11, 22, 33, 44], [22, 33, 44, 55], [33, 44, 55, 66], [44, 55, 66, 77], [55, 66, 77, 88], [66, 77, 88, 99]]
Solution 3:
like this:
my_list = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77,88,99]
m = 0
def incr():
global m
for n in range(len(my_list)):
if n+3 <= len(my_list):
n = m + 3
new_list = my_list[m:n]
print new_list
m +=1
else:
pass
incr()
Post a Comment for "How To Slice Every Nth Element In Index Using Python?"