2013-07-10 5 views
0

한 열의 모든 값이 같으면 true를 반환하는 메서드를 만드는 방법은 무엇입니까? methodhead의다차원 목록의 모든 값이 동일한 지 확인하십시오.

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. 

답변

3

마지막 열의 집합을 만들고; 설정된 이해력이 가장 쉽습니다.

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

또는 함수 : 세트의 길이가 1 인 경우, 그 열의 모든 값이 동일

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

초고속 응답! 대단히 감사합니다. 이것은 완벽하게 작동합니다! –

0

함수가 될 수있다 이렇게 :

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