在python中,给定一个列表列表,如何标识匹配元素的索引?

2024-06-26 14:14:07 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> birds = ['duck', 'chicken', 'goose']
>>> cats = ['tiger', 'lion']
>>> humans = ['human']
>>> at_the_zoo = [birds, cats, humans]

给定一个列表,比如在动物园,我如何定位老虎在哪个列表中?你知道吗

for animal in sum(at_the_zoo, []):
    if "tiger" == animal:
        print "1 help!"

例如,我可以在动物列表中找到老虎,如果我使用enumerate,它会告诉我它在索引3处。我怎么知道它是动物园列表元素1的一部分。 搜索duck会告诉我元素0,等等

谢谢!你知道吗


Tags: the元素列表athumanstigerduck动物园
3条回答

只需建立一个索引:

>>> birds = ['duck', 'chicken', 'goose']
>>> cats = ['tiger', 'lion']
>>> humans = ['human']
>>> at_the_zoo = [birds, cats, humans]
>>> index = {}
>>> for i, arr in enumerate(at_the_zoo):
...   index.update(zip(arr, [i]*len(arr)))
...
>>> index
{'tiger': 1, 'goose': 0, 'lion': 1, 'human': 2, 'duck': 0, 'chicken': 0}
>>> index.get('tiger')
1
>>>

或:

>>> for i, arr in enumerate(at_the_zoo):
...   arr_len = len(arr)
...   index.update(zip(arr, zip([i]*arr_len, range(arr_len))))
...
>>> from pprint import pprint
>>> pprint(index)
{'chicken': (0, 1),
 'duck': (0, 0),
 'goose': (0, 2),
 'human': (2, 0),
 'lion': (1, 1),
 'tiger': (1, 0)}
>>> index.get('tiger')
(1, 0)

贴出的两个答案是find,但是@newtover's对我的口味来说有点太神秘了,@mgilson's并没有按要求回答这个问题。让我试一试。你知道吗

def find_in_inner(lst, target):
    for i, sublst in enumerate(lst):
        if target in sublst:
            return i

>>> birds = ['duck', 'chicken', 'goose']
>>> cats = ['tiger', 'lion']
>>> humans = ['human']
>>> at_the_zoo = [birds, cats, humans]
>>> find_in_inner(at_the_zoo, "tiger")
1

我会这样想:

def find_element(nested_lst, what):
    for idx, sublst in enumerate(nested_lst):
        try:
            idx2 = sublst.index(what)
            return (idx, idx2)
        except ValueError:
            pass

应该有用。你知道吗

示例:

>>> def find_element(nested_lst, what):
...     for idx, sublst in enumerate(nested_lst):
...         try:
...             idx2 = sublst.index(what)
...             return (idx, idx2)
...         except ValueError:
...             pass
... 
>>> birds = ['duck', 'chicken', 'goose']
>>> cats = ['tiger', 'lion']
>>> humans = ['human']
>>> find_element([birds, cats, humans], 'human')
(2, 0)
>>> find_element([birds, cats, humans], 'gator')  # returns None if not found.
>>> find_element([birds, cats, humans], 'tiger')
(1, 0)

值得注意的是,平均而言,list.index是一个O(N)操作,这意味着列表不是测试成员资格的最有效的数据结构。如果您的实际数据支持它,那么可以考虑改用set。你知道吗

相关问题 更多 >