如何将元素插入到列表的程序指定级别?我的解决方案不是很Pythonic式的:
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) 发布于 2013-01-16 02:08:10
给定一系列索引,您可以简单地循环遍历所有索引,除了最后一个遍历嵌套结构的父列表以插入到其中:
listInsertAtDepth(lst, value, indices):
parent = lst
for index in indices[:-1]:
parent = parent[index]
parent.insert(indices[-1], value)你可以添加一个try,except组合来检测你的索引错误:
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方法也不会返回任何内容。
https://stackoverflow.com/questions/14343983
复制相似问题