嵌套列表 Python 3 中的数字平方 [英] Square of Numbers in Nested List Python 3

查看:65
本文介绍了嵌套列表 Python 3 中的数字平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解决的问题是将嵌套列表作为输入,并返回相同的嵌套列表,但每个元素都是该位置先前存在的元素的平方.这是我的代码

<预><代码>>>>定义树图(lst):...对于 lst 中的元素:...如果元素 == 类型(列表):...返回树状图(元素)... 别的:...元素=元素**2...返回lst>>>lst = [1, 2, 3, [4, [5, 6], 7]]>>>打印(树状图(lst))

现在我收到一个错误,说int"对象不可迭代.我假设这意味着它正在尝试为整数类型运行循环,这对我来说没有意义,因为我只为列表类型重新运行该函数.

解决方案

  1. 不要在递归调用中return,一旦返回,你将停止处理所有剩余的元素

  2. element == type(list) 不正确,因为 type(list) 永远不会等于您列表中的任何项目.使用 isinstance 代替

  3. 在基本情况下,您需要通过索引访问元素以反映更改

<小时>

def 树状图(lst):对于 i,enumerate(lst) 中的元素:如果是实例(元素,列表):树状图(元素)别的:lst[i] = lst[i]**2返回列表

输出:

[1, 4, 9, [16, [25, 36], 49]]

The problem I have to solve is one that takes a nested list as an input, and returns the same nested list, except each element is the square of the element that previously existed in that spot. This is my code

>>> def treemap(lst):
...     for element in lst:
...         if element == type(list):
...             return treemap(element)
...         else:
...             element=element**2
...     return lst
>>> lst = [1, 2, 3, [4, [5, 6], 7]]
>>> print(treemap(lst))

Now I am getting an error that is saying 'int' object is not iterable. I'm assuming that means that it's trying to run the loop for an integer type, which doesn't make sense to me, given that I only rerun the function for those of list types.

解决方案

  1. Do not return in the recursive call, you will cease processing all remaining elements once you return

  2. element == type(list) is incorrect, because type(list) is <class 'type'> which will never be equal to any item in your list. Use isinstance instead

  3. In the base case, you'll need to access the element by index to have changes reflected


def treemap(lst):
    for i, element in enumerate(lst):
        if isinstance(element, list):
            treemap(element)
        else:
            lst[i] = lst[i]**2
    return lst

Output:

[1, 4, 9, [16, [25, 36], 49]]

这篇关于嵌套列表 Python 3 中的数字平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆