tags:

views:

139

answers:

8
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 each?

for item in l1:
    if item[0] in l2[0 of the tuple]:
+3  A: 

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)]
Nick Craig-Wood
+1  A: 

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
Ahmed Kotb
This sort method is much slower than the one shown by Nick Craig-Wood.
djc
No downvoting - but this is not pythonic. See Nick's answer for the *right* way of doing this.
Yuval A
yeah you are right :D ....that is my bad
Ahmed Kotb
+5  A: 

First of, don't use list as the name for a variable, as it shadows the built-in list function.

  1. 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]
    
  2. For sorting you can use a lambda expression as shown by others, or you can pass an operator.itemgetter as the key argument to sorted:

    >>> from operator import itemgetter
    >>> sorted(l, key=itemgetter(1))
    [('ba', 4), ('hh', 5), ('gg', 25)]
    
  3. In-place sorting is also possible, using the sort method on lists:

    >>> l.sort(key=itemgetter(1))
    
Stephan202
+1  A: 

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)].

S.Mark
just a question .. isn't converting the list to dict will take time especially if it was a big list ?
Ahmed Kotb
of coz, but if he need to search multiple times, looping each items in list are not good for item retriving, dont you think so? building dict is normally one time, but for searching its very fast.
S.Mark
+1  A: 

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)]
gnibbler
+2  A: 

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')
Mark Byers
Note that for Python 3 this should be `next(...)` instead of `(...).next()`.
Stephan202
Stephan202, I didn't know that (still on 2.5 here) - thanks.
Mark Byers
`next()` is present in 2.6
J.F. Sebastian
`next()` throws `StopIteration` if `'aa'` is not in the list.
J.F. Sebastian
A: 

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)
Dave Kirby
+1  A: 
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
J.F. Sebastian