T
T
tekleworm2018-04-04 10:52:40
Python
tekleworm, 2018-04-04 10:52:40

How to compare index-wise values ​​of two lists?

There are two lists like

list 1 = [23, 56, 78, 69]
list2 = [11, 89, 33, 45]

How to compare pairwise elements of two lists? For example, we take elements of the first and second list by 0 index. These are 23 and 11. We compare them with the one that email. less and put in a separate list. Then, by index 1 (56, 89), we also put it in a separate list. So that we would have a third list with values
list3 = [11, 56,33,45]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-04-04
@tekleworm

result = [min(p) for p in zip(list1, list2)]
or
result = list(map(min, zip(l1, l2)))

D
don_key, 2018-04-04
@don_key

Sergey, your answer is correct, but do you really think that a person with an initial level of knowledge needs exactly the OPTIMAL answer in terms of the amount of code and the functions used? It seems to me that he is now at the level of studying the base - cycles, enumeration, etc. And this would be a better option:

list1 = [23, 56, 78, 69]
list2 = [11, 89, 33, 45]
list3 = [] # создаем заранее пустой список для результата
for i in range(len(list1)): #перебираем элементы списка (в пределах длины первого списка)
    if list1[i] < list2[i]: #сравниваем элементы первого списка с элементами второго списка
        list3.append(list1[i]) #добавляем в пустой список элемент из первого, если он меньше
    else:
        list3.append(list2[i]) #иначе - добавляем элемент из второго списка
print (list3) #выводим итоговый список

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question