且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何深入搜索 Python 列表?

更新时间:2023-11-20 16:17:04

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

>>>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...