2014-10-28 54 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)