在Python中查找列表中的某个项目

时间:2013-05-06 08:50:43

标签: python list

我只是在学习Python,我需要一些关于在列表中搜索项目的建议。我有一个包含列表列表的列表。如何搜索列表中的项目并从同一列表中返回值,如下例所示。

Example: 
myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]

word = 'Green'
return Pear

是否可以在列表中找到第一个实例或第n个实例?

first_instance = 'Red'
return Tomato

last_instance = 'Red'
return Strawberry

5 个答案:

答案 0 :(得分:3)

您可以获取所有这些元素:

instances = [x[1] for x in myList if x[0] == 'Red']

处理instances[0]instances[-1]

要获得第一个,我会使用@ eumoro的方法使用生成器表达式。

答案 1 :(得分:2)

myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]

# first_instance_red
next(elem[1] for elem in myList if elem[0] == 'Red')

# last_instance_red
next(elem[1] for elem in myList[::-1] if elem[0] == 'Red')

答案 2 :(得分:1)

您可以使用collections.defaultdict

创建字典后使用此字典,只需O(1)查找即可找到“红色”或任何其他颜色的任何实例。

>>> myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> for k,v in myList:
    dic[k].append(v)
...     
>>> dic['Red'][0] #first instance
'Tomato'
>>> dic['Red'][-1] #last instance
'Strawberry'
>>> dic["Yellow"][0] #first instance of Yellow
'Lemon'

在此处定义一个简单的函数来处理索引错误:

>>> def solve(n, color, dic):
    try:
        return dic[color][n]
    except IndexError:
        return "Error: {0} has only {1} instances".format(color,len(dic[color]))
...     
>>> dic = defaultdict(list)
>>> for k,v in myList:
    dic[k].append(v)
...     
>>> solve(0, "Red", dic)
'Tomato'
>>> solve(-1, "Red", dic)
'Strawberry'
>>> solve(0, "Yellow", dic)
'Lemon'
>>> solve(1, "Yellow", dic)
'Error: Yellow has only 1 instances'

答案 3 :(得分:0)

行。所有其他答案可能都比这更加pythonic。我只是添加它,因为我认为在开始时,有一些简单的循环有帮助。

def find_first(key, list_of_pairs):
    for pair in list_of_pairs:
        if pair[0] == key:
            return pair[1]
    return None # hey, maybe it isn't in the list at all!

哦,您可以将find_last定义为:

find_last = lambda k, lop: find_first(key, reversed(lop))

因此。在python中你总是可以走这条路。除了你应该真正研究其他答案中提到的list comprehensions

答案 4 :(得分:0)

使用词典理解,一个单行词从列表中制作词典。然后,查询字典。

>>> d={x[0]:x[1] for x in myList}

d等于{'Green': 'Pear', 'Yellow': 'Lemon', 'Red': 'Strawberry'}

>>> d['Green']
'Pear'