简体   繁体   中英

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.

  1. Transpose your list. Use zip to perform this task
  2. Index the first row of your transposed list
  3. Use set to remove duplicate
  4. Determine if no of elements is equal to 1

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM