0

如果一列中的所有值都相同,如何创建返回 true 的方法。

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

方法头示例:

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

2 回答 2

3

从最后一列创建一个集合;集合理解是最简单的。如果集合的长度为 1,则该列中的所有值都相同:

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

或作为一个函数:

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

演示:

>>> 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
于 2013-07-10T11:31:01.857 回答
0

你的功能可以是这样的:

def same_value(Items):
    x = Items[0][2]
    for item in Items:
        if x != item[2]:
            return False
        x = item[2]
    return True
于 2013-07-10T11:41:53.267 回答