如何深入搜索 Python 列表? [英] How can I deep search a Python list?
本文介绍了如何深入搜索 Python 列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Python 中的列表中进行深度搜索.例如,我想知道 5 是否在 my_list
中.
my_list = [2, [3, 4, [2, 3]], 1, [4, [5]]]
我该怎么做?
解决方案
如果你有一个列表列表,你可以使用这种方法
<预><代码>>>>l = [[1,2,3],[4,5,6], [7], [8,9]]>>>[l 中子列表的项目,子列表中的项目][1, 2, 3, 4, 5, 6, 7, 8, 9]>>>5 in [子列表中的项目 l 子列表中的项目]真的首先展平列表并使用 O(n) 搜索它.
如果你的列表看起来像你的例子,我想不出另一种方式这样做而不是使用 for 循环...
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
Which first flattens the list and the searches through it using O(n).
If your list looks like in your example, I can't think of another way to do it than using for-loops...
这篇关于如何深入搜索 Python 列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文