Comparing Lists in Python

Let's say mine list1 = [1,2,3,4]and list2 = [5,6,7,8]. How would you compare the first element 1, in list1with the first element 5, in list2? And 2with 6, 3with 7, etc.

I am trying to use a for loop to do this, but I'm not sure how to do this. I understand that execution for x in list1simply checks an element xfor all elements in list1, but I don’t know how to do this when comparing two lists, as I described.

+3
source share
3 answers

You can move both lists at the same time 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 an iteration of the N loop, you get the Nth element of each list.

+8

. , :

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

, map cmp ( :

>>> map(cmp, [1, 2, 3, 4], [5, 6, 7, 8])
[-1, -1, -1, -1]
+5

, :

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

:

>>> 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]

bools, , .

, zip, , . :

>>> 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]

, , .

+1

Source: https://habr.com/ru/post/1779069/


All Articles