Comparing lists by comparing values of elements of the list in Python

Jenn :

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.

Evan :

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!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=408324&siteId=1