So I have a list of tuple like:
[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
I want this list for a tuple whose number value is equal to something.
So that if I do search(53)
it will return 2
Is is an easy way to do that?
So I have a list of tuple like:
[(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
I want this list for a tuple whose number value is equal to something.
So that if I do search(53)
it will return 2
Is is an easy way to do that?
Hmm... well, the simple way that comes to mind is to convert it to a dict
d = dict(thelist)
and access d[53]
.
EDIT: Oops, misread your question the first time. It sounds like you actually want to get the index where a given number is stored. In that case, try
dict((t[0], i) for i, t in enumerate(thelist))
instead of a plain old dict
conversion. Then d[53]
would be 2.
You can use a list comprehension:
>>> a = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
>>> [x[0] for x in a]
[1, 22, 53, 44]
>>> [x[0] for x in a].index(53)
2
Your tuples are basically key-value pairs--a python dict
--so:
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
val = dict(l)[53]
Edit -- aha, you say you want the index value of (53, "xuxa"). If this is really what you want, you'll have to iterate through the original list, or perhaps make a more complicated dictionary:
d = dict((n,i) for (i,n) in enumerate(e[0] for e in l))
idx = d[53]