How do I check the index of a an element in a list? (Python)
list = [('ba',4), ('hh',5), ('gg', 25)]
How do I do:
list.index('hh') ...and returns 1?
Then, how do I sort it by the 25, 5, 4?
What if I have 2 lists:
list1 = [('ba',4), ('hh',5), ('gg', 25)]
list2 = [('ja',40), ('hgh',88), ('hh', 2)]
how do I do a for ea开发者_StackOverflowch?
for item in l1:
if item[0] in l2[0 of the tuple]:
First of, don't use list
as the name for a variable, as it shadows the built-in list
function.
You can use
enumerate
to pair up list elements and their index:>>> l = [('ba',4), ('hh',5), ('gg', 25)] >>> [i for i, e in enumerate(l) if e[0] == 'hh'] [1]
For sorting you can use a
lambda
expression as shown by others, or you can pass anoperator.itemgetter
as thekey
argument tosorted
:>>> from operator import itemgetter >>> sorted(l, key=itemgetter(1)) [('ba', 4), ('hh', 5), ('gg', 25)]
In-place sorting is also possible, using the
sort
method on lists:>>> l.sort(key=itemgetter(1))
For the finding
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> [ i for i,l in enumerate(L) if l[0] == 'hh' ][0]
1
You need to decide what to do if it is found multiple times or not at all - the above will throw IndexError
if not found and return the first if it is found multiple times.
For the sorting
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=lambda x: x[1])
[('ba', 4), ('hh', 5), ('gg', 25)]
I think Nick's sorting answer is good, but his find method unnecessarily iterates over the entire list, even after it has found a match. With a small change it can be fixed to stop iterating as soon as it finds the first element:
index = (i for i,l in enumerate(l) if l[0] == 'aa').next()
Or in Python 3:
index = next(i for i,l in enumerate(l) if l[0] == 'aa')
to sort the list u can use a custom sort method some thing like this
x = [('ba',4), ('hh',5), ('gg', 25)]
def sortMethod(x,y):
if x[1] < y[1]:return 1
elif x[1] > y[1]:return -1
else: return 0
print x #unsorted
x.sort(sortMethod)
print x #sorted
For the sort, you should use itemgetter
>>> import operator
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=operator.itemgetter(1))
[('ba', 4), ('hh', 5), ('gg', 25)]
you can also have your list in dictionary form
list1 = [('ba',4), ('hh',5), ('gg', 25)]
dict1 = dict(list1)
print dict1['hh']
5
dicts are faster then list if you need to search like that.
btw, overriding built-in type list
to variables are not good idea list = [('ba',4), ('hh',5), ('gg', 25)]
.
from itertools import imap
def find(iterable, item, key=None):
"""Find `item` in `iterable`.
Return index of the found item or ``-1`` if there is none.
Apply `key` function to items before comparison with
`item`. ``key=None`` means an identity function.
"""
it = iter(iterable) if key is None else imap(key, iterable)
for i, e in enumerate(it):
if e == item:
return i
return -1
Example:
L = [('ba', 4), ('hh', 5), ('gg', 25)]
print find(L, 'hh', key=lambda x: x[0])
Output:
1
For the last question, convert list2 into a set:
>>> list1 = [('ba',4), ('hh',5), ('gg', 25)]
>>> list2 = [('ja',40), ('hgh',88), ('hh', 2)]
>>>
>>> wanted = set(a for (a,b) in list2)
>>> for x in list1:
... if x[0] in wanted:
... print x
...
('hh', 5)
精彩评论