[英]How to compare 1st element and operate 2nd element in 2D list in python
[英]Compare 1st element of list from nest list in python
我有一個列表列表,如下所示:
[[a1,a2], [b1,b2],...., [n1]]
我想確定所有這些列表的前幾個元素是否相等?
出於可讀性考慮,除非有理由避免使用列表理解,否則我寧願使用列表理解。
list_of_lists = [[1, 2], [1, 3], [1, 4]]
len(set([sublist[0] for sublist in list_of_lists])) == 1
# True
解決方案非常簡單。
zip
執行此任務 >>> test = [[1, 2], [1, 3], [1, 4]]
>>> len(set(zip(*test)[0])) == 1
True
注意
如果您正在使用PY 3.X,而不是切片,敷調用zip
與next
>>> len(set(next(zip(*test)))) == 1
怎么樣?
>>> 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
還有另一種方式(謝謝彼得·德格洛珀!)
all(sublist[0] == test[0][0] for sublist in test)
這個版本也會短路,因此不需要在每種情況下都檢查每個元素。
與第一個子列表的第一個元素相比,您可以創建第一個元素的列表:
False not in [len(yourList[0])>0 and len(x)>0 and x[0] == yourList[0][0] for x in yourList]
用一個襯板:
>>> 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
嘗試這個...
>>> 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.