简体   繁体   中英

Replacing elements in list when satisfying a specific condition

I would like to change specific elements within a list by adding another list when the value is greater than a value.

Say we have 2 lists:

num_list=[1,5,2,19,28,21]
num_list_2=[2,8,23,81,52,31]
value=3

For the first list I would like it all the values that are greater than 3 to be changed. All values that are greater than 3 I would like it to add to the second list (num_list_2) to create a new list. This is how I approached it:

updated_list=[]
for k in num_list:
 if k > value:
  updated_list=num_list[k]+num_list_2[k]

For some reason I keep getting 'list index out of range,' which I'm not sure as to why. Any help would be greatly appreciated as I am a beginner. Thanks in advance!

Here

num_list=[1,5,2,19,28,21]
num_list_2=[2,8,23,81,52,31]
value=3

updated_list=[]
for k, n in enumerate(num_list):
 if n > value:
    updated_list.append(n + num_list_2[k])
 else:
    updated_list.append(n)
      
print(updated_list)

Your approach is good but you need to get the index to point to the position of the array So, enumerate the list with the index and value and yes append the result to the list.

k is the index and n is the value at array[k]

Note: I also added an else part where you just push the value of first list if is is less than or equals 3

Thanks

def my_function(list_1, list_2, val):

    def choose(index):
        x = list_1[index]
        return x if x <= val else x + list_2[index] 

    return [choose(i) for i in range(len(list_1))]

If you're getting an index exception, it could only be because list_2 is shorter than list_1

Note that the following unit test does pass

def test_my_function():

    list_1 = [1, 5, 2, 19, 28, 21]
    list_2 = [2, 8, 23, 81, 52, 31]
    value = 3

    expected = [1, 13, 2, 100, 80, 52]
    actual = my_function(list_1, list_2, value)

    assert actual == expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM