Comparing lists in Python

后端 未结 3 1476
猫巷女王i
猫巷女王i 2020-12-21 10:20

Say I have list1 = [1,2,3,4] and list2 = [5,6,7,8]. How would I compare the first element, 1, in list1 with the first el

相关标签:
3条回答
  • 2020-12-21 10:53

    The default comparison operators compare lists in lexicographical order. So you can say things like:

    >>> [1, 2, 3, 4] < [5, 6, 7, 8]
    True
    

    If instead you want to compute the elementwise comparison, you can use map and cmp (or any other operator:

    >>> map(cmp, [1, 2, 3, 4], [5, 6, 7, 8])
    [-1, -1, -1, -1]
    
    0 讨论(0)
  • 2020-12-21 10:53

    If your result is going to be a new list, then you can use a list comprehension:

    new_list = [ some_function(i, j) for i, j in zip(list1, list2) ]
    

    Here's a real example of the above code:

    >>> list1 = [1, 2, 3, 4]
    >>> list2 = [1, 3, 4, 4]
    >>> like_nums = [ i == j for i, j in zip(list1, list2) ]
    >>> print like_nums
    [True, False, False, True]
    

    This will make a list of bools that show whether items of the same index in two lists are equal to each other.

    Furthermore, if you use the zip function, there is a way to unzip the result when you are done operating on it. Here's how:

    >>> list1 = [1, 2, 3, 4]
    >>> list2 = [1, 3, 4, 4]
    >>> new_list = zip(list1, list2)         # zip
    >>> print new_list
    [(1, 1), (2, 3), (3, 4), (4, 4)]
    >>> newlist1, newlist2 = zip(*new_list)  # unzip
    >>> print list(newlist1)
    [1, 2, 3, 4]
    >>> print list(newlist2)
    [1, 3, 4, 5]
    

    This could be useful if you need to modify the original lists, while also comparing the elements of the same index in some way.

    0 讨论(0)
  • 2020-12-21 10:58

    You can traverse both lists simultaneously using zip:

    for (x, y) in zip(list1, list2): do_something
    

    The 'zip' function gives you [(1,5), (2,6), (3,7), (4,8)], so in loop iteration N you get the Nth element of each list.

    0 讨论(0)
提交回复
热议问题