Reputation: 45
I have a list of numbers L.
L = [233.0, 0.084, 4.308, 0.0, 2.6208547, 5.1109018, 54.694964, 0.0010984, 54.5804842, 43.473086, 2763.5231162, 28212.5694463, 0.1387176, 0.4591909, 233.0, 0.084, 4.308, 0.0, 2.6208547, 5.1109018, 54.694964, 0.0010984, 54.5804842, 43.473086, 2763.5231162, 28212.5694463, 0.1387176, 0.4591909, 233.0, 0.084, 4.308, 0.0, 2.6208547, 5.1109018, 54.694964, 0.0010984, 54.5804842, 43.473086, 2763.5231162, 28212.5694463, 0.1387176, 0.4591909, 233.0, 0.084, 4.308, 0.0, 2.6208547, 5.1109018, 54.694964, 0.0010984, 54.5804842, 43.473086, 2763.5231162, 28212.5694463, 0.1387176, 0.4591909]
This size of the list is based upon a certain variable, for example if n=4, the list will have 56 elements, if n = 5 it will have 70 elements and so on.
I want to generate an array 'a' of length = n. I want a[0] = L[1]
, a[1] = L[14]
, a[2]=L[28]
and so on. I tried using a nested for loop but did not work out well. Any help would be highly appreciated.
Upvotes: 0
Views: 109
Reputation: 56
If @AKS is right and you mean a[0] = L[0]
answer is:
a = [elem for i, elem in enumerate(L) if i % 14 == 0]
Upvotes: 0
Reputation: 10951
IMHO, easiest one is using slice notation, as mentioned by Joe R's answer. Other options are:
You could've also used the step
parameter in range
function:
>>> def f(lst, step):
new_list = []
for i in range(0,len(lst), step):
new_list.append(lst[i]))
return new_list
>>> f(L,14)
[233.0, 233.0, 233.0, 233.0]
And if you like List comprehensions, then :
>>> [L[i] for i in range(0,len(L), 14)]
[233.0, 233.0, 233.0, 233.0]
Alternative to that is using slice
object:
>>> s = slice(0,len(L), 14)
>>> L[s]
[233.0, 233.0, 233.0, 233.0]
Upvotes: 0
Reputation: 175
#!/usr/bin/python
from array import *
count = 1
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28]
size_of_list = len(list)
my_array = array('i',[])
i = 0
while (count < size_of_list):
my_array.append(list[count])
count = (i+1) *14
i = i+1
print my_array
print "Good bye!"
Upvotes: 1
Reputation: 1243
What about:
indices_list = [i*n for i in xrange(n)]
a = [L[index] for index in indices_list]
Is that what you need?
Upvotes: 1
Reputation: 6583
You can slice L
and create a new list new_list
:
new_list = L[::14]
print (new_list)
output:
[233.0, 233.0, 233.0, 233.0]
Upvotes: 4