J.Olsson
J.Olsson

Reputation: 815

Check if all values in multidimensional list is the same

How can I create a method to return true if all the values in one column is the same.

myListtrue = [['SomeVal', 'Val',True],
             ['SomeVal', 'blah', True]] #Want this list to return true
                                        #because the third column in the list 
                                        #are the same values.

myListfalse = [['SomeVal', 'Val',False],
              ['SomeVal', 'blah', True]] #Want this list to return False
                                         #because the third column in the list 
                                         #is not the same value
same_value(myListtrue) # return true
same_value(myListfalse) # return false

Example of methodhead:

def same_value(Items):
      #statements here
      # return true if items have the same value in the third column.

Upvotes: 0

Views: 834

Answers (2)

Sudipta
Sudipta

Reputation: 4971

Your function can be like this:

def same_value(Items):
    x = Items[0][2]
    for item in Items:
        if x != item[2]:
            return False
        x = item[2]
    return True

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124928

Create a set from the last column; a set comprehension is easiest. If the length of the set is 1, all values in that column are the same:

if len({c[-1] for c in myList}) == 1:
    # all the same.

or as a function:

def same_last_column(multidim):
    return len({c[-1] for c in multidim}) == 1

Demo:

>>> myList = [['SomeVal', 'Val',True],
...          ['SomeVal', 'blah', True]]
>>> len({c[-1] for c in myList}) == 1
True
>>> myList = [['SomeVal', 'Val',False],
...          ['SomeVal', 'blah', True]]
>>> len({c[-1] for c in myList}) == 1
False

Upvotes: 3

Related Questions