问题描述
我有一个包含嵌套列表的列表,我需要知道在这些嵌套列表中搜索的最有效方法.
I have a list that contains nested lists and I need to know the most efficient way to search within those nested lists.
例如,如果我有
[['a','b','c'],
['d','e','f']]
我必须搜索上面的整个列表,找到d"的最有效方法是什么?
and I have to search the entire list above, what is the most efficient way to find 'd'?
推荐答案
使用 list理解,给定:
mylist = [['a','b','c'],['d','e','f']]
'd' in [j for i in mylist for j in i]
产量:
True
这也可以用生成器来完成(如@AshwiniChaudhary所示)
and this could also be done with a generator (as shown by @AshwiniChaudhary)
根据以下评论更新:
这是相同的列表推导式,但使用了更具描述性的变量名称:
Here is the same list comprehension, but using more descriptive variable names:
'd' in [elem for sublist in mylist for elem in sublist]
列表推导部分中的循环结构等价于
The looping constructs in the list comprehension part is equivalent to
for sublist in mylist:
for elem in sublist
并生成一个列表,其中可以使用 in
运算符测试d".
and generates a list that where 'd' can be tested against with the in
operator.
这篇关于在python中搜索嵌套列表的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!