-2

I have a set of lists that I want to compare firstly the sum values of the lists and then individual elements in the event of two or more lists having the same value.

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]

Logic testing for an outright winner is fine but the problem I am having is isolating the lists in the event of a draw – So in the scenario above my_list1 and my_list4 would be isolated for further logic testing as their totals both come to 16.

This is what I have so far

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
user3234931
  • 83
  • 1
  • 3

1 Answers1

0

I suggest creating a single list which holds all of your lists. Then you can use max on that list to find the largest element. Or, if you want the index of the list and not just its value, you can write a max-like method and use that instead.

#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) 

Result:

List # 4 is largest.

A little explanation about key: it's a function that you pass to max, that it uses to determine the comparative value of two items in the sequence. It calls key(someItem) on both items, and whichever item has a larger result, is considered the maximum item between the two of them. The key function I used here returns a tuple. Due to the way tuple comparison works in Python, comparison is done by sum first, then using the first element of each list as a tie breaker.

If you're thinking "but what if the first elements are also the same? I want to use each following item as a tie breaker", then you can modify the key to compare all of them in turn.

idx = index_of_max(lists, key=lambda item: [sum(item)]+item)
Community
  • 1
  • 1
Kevin
  • 74,910
  • 12
  • 133
  • 166