Comparing lists in Python

后端 未结 3 1477
猫巷女王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

    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.

提交回复
热议问题