简体   繁体   English

满足特定条件时替换列表中的元素

[英]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:假设我们有 2 个列表:

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.对于第一个列表,我希望更改大于 3 的所有值。 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.所有大于 3 的值我希望它添加到第二个列表 (num_list_2) 以创建一个新列表。 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] k 是索引,n 是 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注意:我还添加了一个 else 部分,如果小于或等于 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如果您遇到索引异常,那可能只是因为list_2list_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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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