如何检查列表中元素的索引? (蟒蛇)

时间:2009-11-29 11:13:08

标签: python list

list = [('ba',4), ('hh',5), ('gg', 25)]

我该怎么做:

list.index('hh')...并返回1?

然后,我如何按25,5,4?

对其进行排序

如果我有2个列表怎么办?

list1 = [('ba',4), ('hh',5), ('gg', 25)]
list2 = [('ja',40), ('hgh',88), ('hh', 2)]

我如何为每个人做一个?

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

8 个答案:

答案 0 :(得分:5)

首先,不要使用list作为变量的名称,因为它会影响内置的list函数。

  1. 您可以使用enumerate配对列表元素及其索引:

    >>> l = [('ba',4), ('hh',5), ('gg', 25)]
    >>> [i for i, e in enumerate(l) if e[0] == 'hh']
    [1]
    
  2. 对于排序,您可以使用其他人显示的lambda表达式,也可以将operator.itemgetter作为key参数传递给sorted

    >>> from operator import itemgetter
    >>> sorted(l, key=itemgetter(1))
    [('ba', 4), ('hh', 5), ('gg', 25)]
    
  3. 使用列表上的sort方法也可以进行就地排序:

    >>> l.sort(key=itemgetter(1))
    

答案 1 :(得分:3)

发现

>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> [ i for i,l in enumerate(L) if l[0] == 'hh' ][0]
1

如果多次发现或者根本不发现该怎么办?如果找不到,上面会抛出IndexError,如果多次找到,则返回第一个。

用于排序

>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=lambda x: x[1])
[('ba', 4), ('hh', 5), ('gg', 25)]

答案 2 :(得分:2)

我认为尼克的排序答案很好,但是他的发现方法在整个列表中不必要地迭代,即使它找到了匹配。通过一个小的改变,可以修复它,一旦找到第一个元素就停止迭代:

index = (i for i,l in enumerate(l) if l[0] == 'aa').next()

或者在Python 3中:

index = next(i for i,l in enumerate(l) if l[0] == 'aa')

答案 3 :(得分:1)

对列表进行排序你可以使用自定义排序方法这样的事情

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

答案 4 :(得分:1)

您也可以以字典形式列出您的列表

list1 = [('ba',4), ('hh',5), ('gg', 25)]
dict1 = dict(list1)

print dict1['hh']
5
如果您需要像这样搜索,那么

dicts比列表更快。

btw,将内置类型list覆盖到变量上并不是一个好主意list = [('ba',4), ('hh',5), ('gg', 25)]

答案 5 :(得分:1)

对于排序,您应该使用itemgetter

>>> import operator
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=operator.itemgetter(1))
[('ba', 4), ('hh', 5), ('gg', 25)]

答案 6 :(得分:1)

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

示例:

L = [('ba', 4), ('hh', 5), ('gg', 25)]
print find(L, 'hh', key=lambda x: x[0])

输出:

1

答案 7 :(得分:0)

对于最后一个问题,将list2转换为集合:

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