简体   繁体   中英

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.

The same with other lists of 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?

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']]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM