简体   繁体   English

嵌套列表中使用递归的绝对值

[英]Absolute value from nested list using recursion

I have this nested list: 我有这个嵌套列表:

list1 = [2,-6, [8,-12,-12, [4, [-6], -3]], 7, [3.55, -3.55]].

And I have to use recursion to get absolute values of all elements from the lists so output stays as a list: 而且我必须使用递归来从列表中获取所有元素的绝对值,以便输出保持在列表中:

[2, 6, [8, 12, 12, [4, [6], 3]], 7, [3.55, 3.55]].

This is the code: 这是代码:

def rec_abs(a):
    new_list=[]
    for el in a:
        if isinstance(el, list):
            new_list.append(rek_abs(el))
        else:
            new_list.append(el)

    return new_list

print(rek_abs([2,-6, [8,-12,-12, [4, [-6], -3]], 7, [3.55, -3.55]]))

Can You give me some tips to solve it (I dont expect full solultion, just some tips)? 您能给我一些解决问题的技巧吗(我不希望完全解决,只是一些技巧)?

Thank You a lot! 非常感谢!

Everything is perfect, just use abs() to convert it into absolute value 一切都很完美,只需使用abs()将其转换为绝对值

Note : You have typo in code as rec_abs and rek_abs, which I modified it in below code 注意:您在代码中有错别字rec_abs和rek_abs,我在下面的代码中对其进行了修改

def rec_abs(a):
    new_list=[]
    for el in a:
        if isinstance(el, list):
            new_list.append(rec_abs(el))
        else:
            new_list.append(abs(el))
    return new_list

print(rec_abs([2,-6, [8,-12,-12, [4, [-6], -3]], 7, [3.55, -3.55]]))

[2, 6, [8, 12, 12, [4, [6], 3]], 7, [3.55, 3.55]]

For reference, modifying the list in-place is a simple, more efficient alternative, so you should consider this whenever possible. 作为参考,就地修改列表是一种简单,更有效的选择,因此,应尽可能考虑这一点。 When iterating, iterate over the indices, and assign the return value to the ith index. 迭代时,迭代索引,并将返回值分配给第i个索引。

def rec_abs(a):
    for i, el in enumerate(a):
        a[i] = rec_abs(el) if isinstance(el, list) else abs(a[i])

    return a
lst = [2,-6, [8,-12,-12, [4, [-6], -3]], 7, [3.55, -3.55]]

print(rec_abs(lst))
[2, 6, [8, 12, 12, [4, [6], 3]], 7, [3.55, 3.55]]

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

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