首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在列表中以可变深度插入元素的方法?

在列表中以可变深度插入元素的方法?
EN

Stack Overflow用户
提问于 2013-01-16 02:05:45
回答 1查看 219关注 0票数 0

如何将元素插入到列表的程序指定级别?我的解决方案不是很Pythonic式的:

代码语言:javascript
复制
def listInsertDepth(l,e,i,lvl): # Insert element e into list l at depth lvl using list of indices i
    if lvl < 0: # That is, if your depth level is invalid
        return l
    else:
        assert len(i) == lvl+1 # One index for every level, plus for the actual insertion
        s = l # A copy for tampering with
        for index in range(lvl):
            s = s[i[index]]
        s.insert(i[-1],e)
        return listInsertDepth(l,s,i[:-1],lvl-1) 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-16 02:08:10

给定一系列索引,您可以简单地循环遍历所有索引,除了最后一个遍历嵌套结构的父列表以插入到其中:

代码语言:javascript
复制
listInsertAtDepth(lst, value, indices):
    parent = lst
    for index in indices[:-1]:
        parent = parent[index]
    parent.insert(indices[-1], value)

你可以添加一个tryexcept组合来检测你的索引错误:

代码语言:javascript
复制
listInsertAtDepth(lst, value, indices):
    parent = lst
    try:
        for index in indices[:-1]:
            parent = parent[index]
        parent.insert(indices[-1], value)
     except IndexError:
        return None

但就我个人而言,我宁愿得到一个例外,也不愿让它像那样被吞下和丢弃。

请注意,您不应该从函数中返回lst,因为它是就地更改的。像.append().extend()这样的就地修改列表的Python stdlib方法也不会返回任何内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14343983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档