I'm trying to find the indices in a list if two conditions are met, and store those indices in a new list. At the moment I can find the entries on the list that meet the condition, but cannot figure out how to get the list indices.
The list is:
[[0, 1], [1, 0], [0, 2], [1, 1], [2, 0], [0, 3], [1, 2], [2, 1], [3, 0]]
My code so far:
m2=[]
for i in range(0,len(gmcounter)):
if countersum[i]==2 and 2 in gmcounter[i]:
m2.append(gmcounter[i])
print m2
Countersum is a list containing the sums of the list elements, so this returns [[0, 2], [2, 0]]
And I would like m2 to take the index values where the two conditions are met, so I would like it to m1 to take [4,5]
I have an idea it will be something to do with the enumerate function but my attempts to include that so far have not worked
Would greatly appreciate any help!!
Martijn Pieters :
Your i is already the index where the two conditions are met.\n\nUsing enumerate(), possibly combined with zip() would be the more pythonic method:\n\nm2=[]\nfor i, (csum, counter) in enumerate(zip(countersum, gmcounter)):\n if csum == 2 and 2 in counter:\n m2.append(i)\n\n\nor, using a list comprehension:\n\nm2 = [i for i, (csum, counter) in enumerate(zip(countersum, gmcounter)) if csum == 2 and 2 in counter]\n",
2013-05-16T11:55:52