繁体   English   中英

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

[英]Finding a certain item in a list of lists in Python

我只是在学习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

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

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

然后处理instances[0]instances[-1]等。

为了只获得第一个,我将使用生成器表达式使用@eumoro的方法。

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

您可以使用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'

好。 所有其他答案可能比这更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中,您总是可以走这条路。 除了您应该真正研究其他答案提到的列表理解

使用dict理解,一个衬里将dict从列表中剔除。 然后,查询字典。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM