Find the index of the list of fuzzy tuples at the first index of the tuple

I am trying to get the index of a list of 2-tuples in Python where index is 0 of each tuple 'a'

:

list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]

      

So I'm using the following list comprehension to figure out which index is returned, right?

index_list = [x for x, y in enumerate(list_of_tuples) if x[0] == 'a']

      

Which gives the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-22-5d47328b7d9a> in <module>()
----> 1 index_list = [x for x, y in enumerate(list_of_tuples) if x[0] ==     'a']

TypeError: 'int' object is not subscriptable

      

How do I find out the index associated with a list of tuples lookup for the value at the 0th index being equal 'a'

?

+3


source to share


4 answers


Use a value y

for non-index comparison x

:

list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]
index_list = [x for x, y in enumerate(list_of_tuples) if y[0] == 'a']

      



Now index_list

there is [0, 1, 2]

.

+1


source


x

- index. You should be able to access the first item y -> y[0]

. y

- every tuple in your list. You can also unpack:

list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]
index_list = [ind for ind,  (a, _) in enumerate(list_of_tuples) if a == 'a']
print(index_list)
[0, 1, 2]

      

If you are print(list(enumerate(list_of_tuples)))

, you can see that the first element is the index and the second is your tuple:



[(0, ('a', 1)), (1, ('a', 2)), (2, ('a', 3))]

      

So you are trying to index 0 -> 0[0]

with x[0]

.

+1


source


First, I recommend that you check your details.

list_of_tuples = [('a', 1), ('a', 2), ('a', 3)]
print list(enumerate(list_of_tuples))
# [(0, ('a', 1)), (1, ('a', 2)), (2, ('a', 3))]
    ^   ^-----^
    x     y

      

Once you understand how to unpack data, it's easy to do.

index_list = [x for x, y in enumerate(list_of_tuples) if y[0] == 'a']
print index_list

      

+1


source


for x,y in enumerate(my_tuples):
    print x,"=x"
    print y,"=y"

      

you should immediately see a problem with x[0] == 'a'

I believe

index_list = [x for x, y in enumerate(list_of_tuples) if y[0] == 'a']

      

should work better for you

0


source







All Articles