如果一列中的所有值都相同,如何创建一个返回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.
答案 0 :(得分: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
答案 1 :(得分:0)
你的功能可以是这样的:
def same_value(Items):
x = Items[0][2]
for item in Items:
if x != item[2]:
return False
x = item[2]
return True