[英]Modifying a list outside of recursive function in Python
There is a multidimensional list with not clear structure: 存在一个结构不明确的多维列表:
a=[[['123', '456'], ['789', '1011']], [['1213', '1415']], [['1617', '1819']]]
And there is a recursive function, which operates the list: 还有一个递归函数,用于操作列表:
def get_The_Group_And_Rewrite_It(workingList):
if isinstance(workingList[0],str):
doSomething(workingList)
else:
for i in workingList:
get_The_Group_And_Rewrite_It(i)
Through time the get_The_Group_And_Rewrite_It()
should get a list, for instance, ['123','456']
, and as soon as it get it, doSomething
function should rewrite it with ['abc']
in entire list. 随着时间的get_The_Group_And_Rewrite_It()
应该会得到一个列表,例如['123','456']
,并且一旦获得, doSomething
函数就应该在整个列表中用['abc']
重写它。
The same with other lists of format[str,str,...]
. 与其他format[str,str,...]
列表相同。 In the end I should get something like 最后我应该得到类似
a=[[['abc'], ['abc']], [['abc']], [['abc']]]
I see it would be easy in C++, using *links
, but how to do that in Python? 我看到使用*links
在C ++中会很容易,但是如何在Python中做到这一点呢?
For this case, you can use slice assignment: 对于这种情况,可以使用切片分配:
>>> a = [[['123', '456']]]
>>> x = a[0][0]
>>> x[:] = ['abc']
>>> a
[[['abc']]]
>>> def f(workingList):
... if isinstance(workingList[0],str):
... workingList[:] = ['abc']
... else:
... for i in workingList:
... f(i)
...
>>> a=[[['123', '456'], ['789', '1011']], [['1213', '1415']], [['1617', '1819']]]
>>> f(a)
>>> a
[[['abc'], ['abc']], [['abc']], [['abc']]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.