V
V
vert212020-06-13 15:36:54
Python
vert21, 2020-06-13 15:36:54

How to compare values ​​of two arrays?

Good afternoon! There was a question about comparing two arrays in which there are 5 elements each (the second array is filled with input, and the first is given). I need to compare them and display the number of identical elements in one value. For example:
[1, 2, 3, 4, 5]
[2, 2, 3, 7, 5] (input)
python output:
[2, 3, 5]
Please help!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Kuts, 2020-06-13
@fox_12

a = [1, 2, 3, 4, 5]
b = [2, 2, 3, 7, 5]

[x for i,x in enumerate(a) if x==b[i]]
[2, 3, 5]

or
list(set(a).intersection(b))
[2, 3, 5]

depending on what is required

0
0xD34F, 2020-06-13
@0xD34F

[ arr1[i] for i in range(len(arr1)) if arr1[i] == arr2[i] ]

# или

[ n for i, n in enumerate(arr1) if n == arr2[i] ]

# или

[ n for n, m in zip(arr1, arr2) if n == m ]

D
Dmitry, 2020-06-13
@LazyTalent

>>> [x[0] for x in zip([1, 2, 3, 4, 5], [2, 2, 3, 7, 5]) if x[0]==x[1]]
[2, 3, 5]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question