[英]Check first elements of a list of lists
I have a list which looks like this: 我有一个看起来像这样的清单:
List = [['name1','surname1'], ['name2','surname2'],['name3','surname3']]
I would like to check if "name1" is in the object "List". 我想检查“ name1”是否在对象“列表”中。 I have tried:
我努力了:
if 'name1' in List:
print True
else:
print False
and the output is 'False'. 并且输出为“ False”。 Any idea how to create a sublist (or something similar) to check the first element of every sub-list without looping through all the elements of the main list?
任何想法如何创建一个子列表(或类似的东西)来检查每个子列表的第一个元素,而不循环遍历主列表的所有元素?
POSSIBLE SOLUTION 可能的解决方案
What I have thought about is: 我想到的是:
for i in range(0, len(List)):
if List[i][0] == 'name1':
print True
but I want to avoid exactly this iteration with something more optimized, if possible. 但我想尽可能避免使用更优化的方法来进行此迭代。
You can use a generator expression: 您可以使用生成器表达式:
>>> 'name1' in (x[0] for x in List)
True
This will short-circuit as soon as 'name1'
is found and won't create any unnecessary list in memory. 一旦找到
'name1'
,它将短路,并且不会在内存中创建任何不必要的列表。
Related: List comprehension vs generator expression's weird timeit results? 相关: 列表理解与生成器表达式的奇怪时间结果?
I suggest using a dictionary, which seems more suitable here. 我建议使用字典,在这里看起来更合适。
But if a list of lists is to be used, you can have such a code: 'name1' in [list[0] for list in List]
但是,如果要使用列表列表,则可以使用这样的代码:
'name1' in [list[0] for list in List]
You can do it with: 您可以执行以下操作:
if 'name1' in [l[0] for l in List]:
You can also add an if l
at then end of the list comprehension just in case there's an empty list around: 您还可以在列表理解的末尾添加
if l
,以防万一周围有一个空列表:
if 'name1' in [l[0] for l in List if l]: # safe if there's an empty list
More idiomatic way to do this, is to use any
function 更为惯用的方法是使用
any
功能
>>> any('name1' == current_list[0] for current_list in my_list)
True
This also short circuits on the first occurrence of name1
. 这也会在第一次出现
name1
使之短路。
Edit : In case, your name1
can be anywhere in the sub-list, you can use the in
operator 编辑:如果您的
name1
可以在子列表中的任何位置,则可以使用in
运算符
>>> any('name1' in current_list for current_list in my_list)
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.