[英]Compare 1st element of list from nest list in python
I have a list of lists like following : 我有一个列表列表,如下所示:
[[a1,a2], [b1,b2],...., [n1]]
and I want to find whether the first elements of all these lists are equal? 我想确定所有这些列表的前几个元素是否相等?
I'd prefer to do this with a list comprehension unless there's a reason to avoid it, for readability's sake. 出于可读性考虑,除非有理由避免使用列表理解,否则我宁愿使用列表理解。
list_of_lists = [[1, 2], [1, 3], [1, 4]]
len(set([sublist[0] for sublist in list_of_lists])) == 1
# True
The solution is quite straight forward. 解决方案非常简单。
zip
to perform this task 使用zip
执行此任务 >>> test = [[1, 2], [1, 3], [1, 4]]
>>> len(set(zip(*test)[0])) == 1
True
Note 注意
If you are using Py 3.X, instead of slicing, wrap the call to zip
with next
如果您正在使用PY 3.X,而不是切片,敷调用zip
与next
>>> len(set(next(zip(*test)))) == 1
How about? 怎么样?
>>> from operator import itemgetter
>>> test = [[1, 2], [1, 3], [1, 4]]
>>> len(set(map(itemgetter(0), test))) == 1
True
>>> test.append([2, 5])
>>> test
[[1, 2], [1, 3], [1, 4], [2, 5]]
>>> len(set(map(itemgetter(0), test))) == 1
False
And another way would be (Thanks, Peter DeGlopper!) 还有另一种方式(谢谢彼得·德格洛珀!)
all(sublist[0] == test[0][0] for sublist in test)
This version would short-circuit too, so it wouldn't need to check every element in every case. 这个版本也会短路,因此不需要在每种情况下都检查每个元素。
与第一个子列表的第一个元素相比,您可以创建第一个元素的列表:
False not in [len(yourList[0])>0 and len(x)>0 and x[0] == yourList[0][0] for x in yourList]
With a one liner: 用一个衬板:
>>> sample = [[1, 2], [1, 3], [1, 4]]
>>> reduce(lambda x, y: x if x == y[0] else None, sample, sample[0][0])
1
>>> sample = [[0, 2], [1, 3], [1, 4]]
>>> reduce(lambda x, y: x if x == y[0] else None, sample, sample[0][0])
None
Try this... 尝试这个...
>>> test = [[1, 2], [1, 3], [1, 4]]
>>> eval("==".join(map(lambda x: str(x[0]), test)))
True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.