Suppose you have an array p
:
p=[['0', '9', '10', '13'], ['1', '8', '10', '14'],
['2', '7', '9', '15'], ['3', '2', '8', '18'],
['4', '1', '7', '19'], ['5', '1', '2', '20'],
['6', '2', '4', '21'], ['7', '1', '3', '22'],
['8', '4', '6', '25'], ['9', '3', '5', '26'],
['10', '5', '6', '27'], ['11', '8', '10', '28'],
['12', '7', '9', '31'], ['13', '1', '2', '32'],
['14', '4', '6', '33'], ['15', '3', '5', '34']]
I am interested in knowing the indexes of elements based on a partial string that should always match with elements in p
at positions [1]
and [2]
(In p
that would be 9,10
, 8,10
, 7,9
, 2,8
etc). For example, I would like to know the indexes of elements containing the partial string '1','2'
. In such case, the indexes should be: [5,13]
that corresponds to elements:
['5', '1', '2', '20']
['13', '1', '2', '32']
I found this related question in stackoverflow: python - find index postion in list based of partial string. However, when I have tried with only 2
as the partial string I have got the following result (which is perfect):
>>> indices = [i for i, s in enumerate(p) if '2' in s]
>>> indices
[2, 3, 5, 6, 13]
>>>
But then, if I try with ('1','2')
I get nothing:
>>> indices = [i for i, s in enumerate(p) if ('1','2') in s]
>>> indices
[]
How should I write the partial string in the if
so that this code work?. I really don't understand why it is not working. I'd be happy if somebody could help me to understand this. I have tried: putting the partial string between []
, define it as an array before the conditional and that doesn't work either. Is there another way to accomplish the same task?, because I am aware that the mere use of the code presented in the link mentioned above does not search matches in positions [1]
and [2]
.