>>> birds = ['duck', 'chicken', 'goose']
>>> cats = ['tiger', 'lion']
>>> humans = ['human']
>>> at_the_zoo = [birds, cats, humans]
给出像at_the_zoo这样的列表,如何定位哪个列表老虎在其中?
for animal in sum(at_the_zoo, []):
if "tiger" == animal:
print "1 help!"
例如,我可以在动物列表中找到老虎,如果我使用枚举,它会告诉我它在索引3,如何知道它是列表at_the_zoo元素1的一部分。搜索鸭子会告诉我元素0,等等。
谢谢!
发布于 2014-06-27 22:35:52
我会想:
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
。
发布于 2014-06-27 23:14:06
只需构建一个索引:
>>> 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)
发布于 2014-06-27 23:44:49
这两个帖子的答案都找到了,但是@newtover对我的口味来说太神秘了,@mgilson没有回答所问的问题。让我试一试。
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
https://stackoverflow.com/questions/24461679
复制相似问题