Reputation: 1
how to compare more then one list, below works ok for just 2 lists but what if more needed
while (list1[0:1] == list2[0:1]):
if list1[1:2] > list2[1:2]:
print('list 1 wins')
elif list1[2:3] > list2[2:3]:
print('list 1 wins!')
elif list1[3:4] > list2[3:4]:
print('list 1 wins')
elif list1[4:5] > list2[4:5]:
print('list 1 wins')
elif list1[5:5] == list2[5:5]:
print('its a tie')
else:
print('list 2 wins')
break
Upvotes: 0
Views: 106
Reputation: 30258
As pointed out lists can be directly compared without iterating through them.
But when you want to work with multiple lists at the same time it is idiomatic to use zip()
, e.g.:
for i1, i2 in zip(list1, list2):
if i1 > i2:
print("List 1 wins")
break
if i2 > i1:
print("List 2 wins")
break
else:
print("It's a tie")
Upvotes: 1
Reputation: 55469
As bereal says, you can just use list comparison for this. If ties weren't an issue, you could just use max()
to determine a winner, but to handle ties you need to sort the whole collection of lists.
Eg, this code will handle any number of lists.
list1 = [50,9,5,4,5]
list2 = [50,9,8,1,6]
list3 = [50,9,8,1,5]
lists = [(seq, i) for i, seq in enumerate((list1, list2, list3), 1)]
lists.sort(reverse=True)
if lists[0][0] == lists[1][0]:
print("it's a tie")
else:
print("list {0} wins: {1}".format(lists[0][1], lists[0][0]))
output
list 2 wins: [50, 9, 8, 1, 6]
If you change list2
back to [50, 9, 8, 1, 6]
, then it's a tie
will get printed.
lists
is a list of tuples, with each tuple containing one of the original lists and its index number, so we can identify lists after the tuples have been sorted. The sorting will compare the lists, and if two lists are identical, then the indices will also be compared, but that doesn't affect the desired outcome here.
BTW, list1[1:2] > list2[1:2]
is wasteful. It creates a new pair of single element lists & compares them. It's easier to just compare the elements themselves, eg list1[1] > list2[1]
.
Upvotes: 0
Reputation: 34272
Lists and tuples can be compared just like that assuming that the matching elements are comparable:
>>> list1=[50,9,5,4,5]
>>> list2=[50,9,8,1,5]
>>> list1 > list2
False
>>> list1 < list2
True
That also means that you can order any number of lists:
>>> lists = [list1, list2, list3]
>>> lists.sort()
Upvotes: 1
Reputation: 588
Did you consider using a for-loop?
The syntax is:
for value in list:
# do something
print value
and then there is the (zip function)
list1 = [1,2]
list2 = [a,b]
zip(list1, list2) # = [(1,a),(2,b)]
With these two tools one is able to provide a really pythonic solution to your problem.
Upvotes: 0