I'm pretty new to Python and needed some help with part of a project. I am trying to compare which list is bigger between two lists of numbers, for example [1,2,3,4,5,6] and [6,5,4,3,2,1]. When the lengths of the lists are the same, I need to scan the lists from left to right comparing digit by digit. I thought to start with a for loop but I'm not sure how to implement this.
-
sorry I need to know which number is greater between two numbers like 123,456 and 654,321 but these numbers have been put into listsJenn– Jenn2020-04-01 17:08:14 +00:00Commented Apr 1, 2020 at 17:08
Add a comment
|
2 Answers
you may use the built-in function max with the parameter key:
l1 = [1,2,3,4,5,6]
l2 = [6,5,4,3,2,1]
max([l1, l2], key=lambda x: (len(x), x))
or you may use (suggested by @Ch3steR):
max(l1,l2,key=lambda x:(len(x),x))
So you're saying you basically need to compare and see if 123,456 is greater than 654,321?
You could make a function that accepts two input lists, like this:
def compare(list1, list2):
first_number = int(''.join(str(x) for x in list1))
second_number = int(''.join(str(x) for x in list2))
if first_number > second_number:
return first_number
else:
return second_number
This essentially converts each list into a string, and casts the list as an int, and then returns the larger int.
Hope that helps!
1 Comment
Evan
No problem! If I helped I'd appreciate if you could mark the answer as correct :D