2014-10-28 3 views
-2

나는 목록의 합계 값을 먼저 비교하고 같은 값을 가진 두 개 이상의 목록이있는 경우 개별 요소를 비교하기를 원하는 목록 집합을 가지고 있습니다. 명백한 승자에 대한python3의 값을 기반으로 목록 분리하기

my_list1 = [2, 3, 2, 4, 5] 
my_list2 = [1, 3, 2, 3, 2] 
my_list3 = [1, 1, 2, 2, 2] 
my_list4 = [3, 2, 2, 4, 5] 

로직 테스트는 괜찮하지만 난 데 문제는 무승부의 경우에 목록을 분리입니다 - 자신의 합계로 더 로직 테스트를 위해 격리 될 my_list1my_list4 위의 시나리오에서 그래서 둘 다 16입니다.

이것은 내가 지금까지

my_list1=[1,1,2,2,2] 
my_list2=[1,1,1,1,2] 
my_list3=[2,2,1,1,2] 


my_list1Total=sum(my_list1) 
my_list2Total=sum(my_list2) 
my_list3Total=sum(my_list3) 

if my_list1Total>my_list2Total and my_list1Total>my_list3Total: 
    print("List one has the higest score") 
elif my_list2Total>my_list1Total and my_list2Total>my_list3Total: 
    print("List two has the higest score") 
elif my_list3Total>my_list2Total and my_list3Total>my_list1Total: 
    print("List three has the higest score") 
else: 
    print("Draw") 

##so now I want to compare the lists with the same total but this time by the first element in the list. In this case it would be my_list1[0] and my_list3[0] that would be compared next. The winner having the highest value in position 0 of the drawing lists 
+0

무엇을 시도 했습니까? 출력물은 무엇이고 대신 무엇을 기대합니까? – jonrsharpe

답변

0

나는 당신의 모든 목록을 보유하고 하나의 목록을 작성 제언 것입니다. 그런 다음 해당 목록에서 max을 사용하여 가장 큰 요소를 찾을 수 있습니다. 또는 값만이 아닌 목록의 색인을 원할 경우 최대 유사 방법을 작성하여 대신 사용할 수 있습니다.

#like the built-in function `max`, 
#but returns the index of the largest element 
#instead of the largest element itself. 
def index_of_max(seq, key=lambda item:item): 
    return max(range(len(seq)), key=lambda idx: key(seq[idx])) 

lists = [ 
    [2, 3, 2, 4, 5], 
    [1, 3, 2, 3, 2], 
    [1, 1, 2, 2, 2], 
    [3, 2, 2, 4, 5] 
] 

idx = index_of_max(lists, key=lambda item: (sum(item), item[0])) 
#add one to this result because Python lists are zero indexed, 
#but the original numbering scheme started at one. 
print "List # {} is largest.".format(idx+1) 

결과 :

List # 4 is largest. 

key에 대해 조금 설명 : 그것은 순서의 두 항목의 비교 값을 결정하는 데 사용하는, 당신은 max에 전달하는 기능입니다. 두 항목 모두에서 key (someItem)를 호출하고 더 큰 결과를 갖는 항목은 두 항목 사이의 최대 항목으로 간주됩니다. 여기에서 사용한 핵심 함수는 터플을 반환합니다. tuple comparison works in Python 방식으로 인해 먼저 합계를 비교 한 다음 각 목록의 첫 번째 요소를 타이 브레이커로 사용합니다.

"첫 번째 요소도 동일하면? 다음 항목을 타이 브레이커로 사용하고 싶습니다."라고 생각하면 키를 수정하여 차례대로 비교할 수 있습니다.

idx = index_of_max(lists, key=lambda item: [sum(item)]+item)