2014-10-28 38 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 2014-10-28 11:16:29

回答

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一個功能,它使用來確定序列中兩個項目的比較值。它調用兩個項目上的鍵(someItem),並且哪個項目具有更大的結果,被認爲是它們之間的最大項目。我在這裏使用的關鍵函數返回一個元組。由於tuple comparison works in Python的方式,首先通過總和進行比較,然後使用每個列表的第一個元素作爲聯絡斷路器。

如果你在想「但是如果第一個元素也是一樣的?我想用下面的每個項目作爲決勝盤」,那麼你可以修改這個鍵來依次比較它們。

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