我怎样才能深深的搜索Python列表? [英] How can I deep search a Python list?

查看:104
本文介绍了我怎样才能深深的搜索Python列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中的列表深的搜索。例如,我想知道,5是 my_list 或没有。

I want to deep search in a list in Python. For example, I want to know that 5 is in my_list or not.

my_list = [2, [3, 4, [2, 3]], 1, [4, [5]]]

我怎么能这样做?

How can I do that?

推荐答案

如果你有一个列表的列表,你可以使用这种方法。

If you have a list of lists, you can use this approach

>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> [item for sublist in l for item in sublist]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 5 in [item for sublist in l for item in sublist]
True

这首平坦的列表,并通过它使用澳搜索(N)。

Which first flattens the list and the searches through it using O(n).

如果您的列表看起来像你的榜样,我想不出另一种方式
这样做比使用for循环...

If your list looks like in your example, I can't think of another way to do it than using for-loops...

这篇关于我怎样才能深深的搜索Python列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆