Question: Obtain Position Of Numbers In Python Array
0
6.8 years ago by
rosarylimyt70
rosarylimyt70 wrote:

Hey all,

I'm having problems with obtaining the range of positions of certain numbers in an array. As an example, I have:

[0,0,0,1,1,1,1,1,1,1,0,0,0,1,1,0]

as my array. I would like Python to tell me which are the range of positions where I will find ONLY zeros.

i.e. it should spit out: [0,2] , [10,12] , [15] as answers to me.

The script I cracked my brains over is:

``````s = 0
e = 0
prev_char = ''
s_e_list = []
for char in cover_array:
cnt += 1
#print char, cnt
if char == '1' and prev_char != '1':
e = cnt - 1
#add the start and end to a list
s_e = "%d_%d"%(s,e)
print s_e, s, e
s_e_list.append(s_e)
#intialize start to zero
s = 0
e = 0
#print char
elif s == 0 and prev_char == '1':
s = cnt
print s
elif char == '0':
if s == 0:
s = cnt
prev_char = char

print s_e_list
``````

But the results weren't accurate, it seems to fall short of a few positions. Am I doing it wrongly?

All feedback are welcomed =]

Rosary

array python position index • 2.5k views
modified 6.8 years ago by David W4.7k • written 6.8 years ago by rosarylimyt70
3

You should ask general programming questions on stackoverflow.com, not here. Your question is unrelated to bioinformatics.

2
6.8 years ago by
David W4.7k
New Zealand
David W4.7k wrote:

One way is to use the `groupby` function from `itertools`, which splits a list into runs of identical elements.

One approach:

``````from itertools import groupby
array = [0,0,0,1,1,1,1,1,1,1,0,0,0,1,1,0]

for group,k in groupby(enumerate(array), lambda(i,x): x):
print group, [i for i,element in k]

## 0 [0, 1, 2]
## 1 [3, 4, 5, 6, 7, 8, 9]
## 0 [10, 11, 12]
## 1 [13, 14]
## 0 [15]
``````
1

Please don't answer off topic questions. This is diluting the overall quality of this site.

I hadn't seen your comment when I answered, and assumed there was a bioinformatics angle hiding in the questions. Go ahead and delete/close if Rosary doesn't provide one.

Thank you so much David.

Michael: I'm trying to use an array here to identify all coordinates (start & end positions) of unpredicted ORFs. In that sense, all the 1s are actually predicted ORFs and 0s would be the unpredicted ones - which I'm interested. As such, I'm just trying to be straightforward when seeking help and post a 'shorter' example of the problem shown as my original post. However, if you still reckon my question is of no relevance to bioinformatics still, then sure, I'll post them on stackoverflow in future, no problem. I merely felt that there's a more prestigous pool of people with expertise to help in an ASAP manner here on Biostars that's all.