我有一组列表,我想首先比较列表的总和值,然后在两个或多个列表具有相同值的情况下单个元素。
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_list1
和my_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 :(得分:0)
我建议创建一个包含所有列表的列表。然后,您可以使用该列表上的max
来查找最大的元素。或者,如果您想要列表的索引而不仅仅是它的值,您可以编写类似于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)