【问题标题】:Dynamically accessing an element in a nested list python动态访问嵌套列表python中的元素
【发布时间】:2021-10-29 21:21:18
【问题描述】:

我有一个函数可以遍历列表并在元素为整数时打印元素,如下所示:

def fnc(s, d = 0, lst=[0]):
    if isinstance(s, (tuple, list)):
        for i, elt in enumerate(s):
            if isinstance(elt, int):
                # print(f'{s}, {d}, {i}, {lst}')
                daccess(s, d, i, lst)
            else:
                lst.append(i)
                fnc(elt, d+1, lst)
                lst.pop(-1)

daccess定义如下:

def daccess(lst, d, i, indices):
    if d == 0:
        print(lst[i])
    else:
        lst_index = lst[indices.pop(1)]
        daccess(lst_index, d-1, i, indices)

fnc 应该将s, d, i, lst 作为参数传递给daccess,其中 s 是嵌套列表,d 是要访问的元素的深度,i 是它的索引位置,lst 是遇到的每个嵌套列表的索引。例如用 (s=[1,2,[3,[4,5,6]]], d=2, i=1, lst=[0,2,1]) 可以翻译成 s[2] [1][1] == 5。

当我将fnc 在第 5 行(已注释掉)打印的参数传递给 daccess 时,它按预期工作:

daccess(s, 0, 1, [0])
daccess(s, 0, 0, [0])
...
daccess(s, 1, 0, [0, 8])
daccess(s, 1, 1, [0, 8])
etc...

但是,当调用 daccess inside fnc 时(所以只调用 fnc(s) 我得到这个错误:

1
2
33
6425
64
Traceback (most recent call last):
  File "fa.py", line 56, in <module>
    fnc(s)
  File "fa.py", line 20, in fnc
    fnc(elt, d+1, lst)
  File "fa.py", line 17, in fnc
    daccess(s, d, i, lst)
  File "fa.py", line 8, in daccess
    lst_index = lst[indices.pop(1)]
IndexError: pop index out of range

s 定义如下: 小号 = ( 1, 2, 33,6425, ( 3, 4, 44, ( 5、66、63225、25673547、88 ), ( 64,121 ) ), 9、10、11、 ( 89, 90 ) )

(我知道这是一个元组的元组,但只是假设它是一个列表的列表。我有一个单独的函数可以在调用其他任何东西之前将一个元组的元组转换为一个列表的列表)

我尝试使用 sindices 的深层副本,但我得到了同样的错误。我确定如果我在主文件中使用正确的参数调用daccess,它会起作用,但我真的不知道在fnc 中调用它时出了什么问题。

感谢任何关于为什么会发生这种情况的帮助。

【问题讨论】:

  • 尝试用lst=None替换默认参数lst=[0],然后在正文if lst is None: lst = [0]中。 lst 仅在创建时生成一次,并且您将其弹出两次。
  • @RobinGertenbach 我仍然得到完全相同的错误。问题是,当在主文件中调用 daccess 时,它可以为我尝试访问的任何元素使用正确的参数。问题是在 fnc 内部调用它时。
  • 啊,是的,我明白了。你的预期输出是什么?例如需要 64 吗?还是您希望它继续 9、10、11?
  • 好吧,fnc 应该遍历s 中的所有整数,所以我希望在我的问题中使用与s 相同的顺序。即 1、2、33、6425...89、90
  • 相关问题:Flatten an irregular list of lists。你可以写flatten,在你的嵌套列表上调用flatten,然后打印结果。

标签: python list recursion nested


【解决方案1】:

根据您的评论,您希望保持列表结构完整,但对每个不可迭代元素(推断)执行一些操作 (str)。

如何避免所有的弹出和索引?

from typing import Iterable
def fnc(s):
  if isinstance(s, Iterable) and not isinstance(s, (str, bytes)):
    return [fnc(e) for e in s]
  else:
    return str(s)

【讨论】:

  • 这是一个巧妙的解决方案,可以根据我的实际需要进行一些修改,谢谢!我会接受答案,但它没有回答仍然困扰我的原始问题。不过谢谢你,我也可以用这个。
【解决方案2】:

受到相关问题Flatten an irregular list of lists的启发。

from collections.abc import Iterable

def map_in_depth(f, l):
  return [(map_in_depth(f, e) if isinstance(e, Iterable) and not isinstance(e, (str,bytes)) else f(e)) for e in l]

或者,如果您知道该列表仅包含 ints 和 lists:

def map_in_depth(f, l):
  return [(f(e) if isinstance(e, int) else map_in_depth(f, e)) for e in l]

对于这两个版本,我得到:

map_in_depth(lambda x: 2*x, [1,2,[3,[4,5,6]]])
# [2, 4, [6, [8, 10, 12]]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    相关资源
    最近更新 更多