Pavel  Shlepnev
Pavel Shlepnev

Reputation: 165

How to replace an item in a list depending on an item in another list?

I have two equal lists, their values are connected to each other:

list1 = [29, 4, 15, 4, 5, 5]
list2 = [57.49999999999999, 89.74358974358975, 78.94736842105263, 100.0, 94.44444444444444, 57.89473684210527]

How do I change the i-th value in list1 to 40 if the corresponding i-th value in list2 is less than 65.0?

Upvotes: 0

Views: 71

Answers (3)

skulden
skulden

Reputation: 423

You have to iterate on list2 to find which index has a value smaller than 65.0. With this index number you can replace nth value in list1:

list1 = [29, 4, 15, 4, 5, 5]
list2 = [57.49999999999999, 89.74358974358975, 78.94736842105263, 100.0, 
94.44444444444444, 57.89473684210527]

for i in range(0, len(list1)):

  if list2[i] < 65.0:
    list1[i] = 40


print(list1)

Upvotes: 1

boot-scootin
boot-scootin

Reputation: 12515

A list comprehension with the ternary operator and zip should do the trick:

[40 if list2_val < 65.0 else list1_val
    for list1_val, list2_val in zip(list1, list2)]
Out[2]: [40, 4, 15, 4, 5, 40]

FWIW, this more compact (but perhaps more difficult to read) syntax will produce an identical result to that of Tobias's answer.

Depending on how long your lists are, you might try using pandas and numpy:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'list1': list1, 'list2': list2})
>>> df
   list1       list2
0     29   57.500000
1      4   89.743590
2     15   78.947368
3      4  100.000000
4      5   94.444444
5      5   57.894737
>>> df['list1_new'] = np.where(df['list2'] < 65, 40, df['list1'])
   list1       list2  list1_new
0     29   57.500000         40
1      4   89.743590          4
2     15   78.947368         15
3      4  100.000000          4
4      5   94.444444          5
5      5   57.894737         40

Upvotes: 2

user1781434
user1781434

Reputation:

You should use zip as I wrote in a comment, I think that would be the cleanest solution.

new_list1 = []
for a, b in zip(list1, list2):
    if b < 65.0:
        new_list1.append(40)
    else:
        new_list1.append(a)

Upvotes: 2

Related Questions