>>> 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,依此类推。
谢谢!
我会想这样的:
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)操作,这意味着列表并不是测试成员资格的最有效数据结构。如果您的实际数据支持它,那么可能值得考虑使用a set
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句