简体   繁体   English

替换列表中的值

[英]Replace values in list of lists

Python 3. Windows 10. Python 3. Windows 10。

I have a hierarchical list and I want to change their values with the values specified. 我有一个层次结构列表,我想用指定的值更改它们的值。

For example: I have hierarchical list 例如:我有层次结构列表

l = [[[0, 4], 1], [2, 3], 5]]

and I have a dictionary 我有一本字典

{0: 'da-1.txt',
 1: 'da-2.txt',
 2: 'en-1.txt',
 3: 'en-2.txt',
 4: 'it-1.txt',
 5: 'it-2.txt'}

I want to replace values of the list with the values of the dictionary correspondingly without breaking the list hierarchy structure. 我想用字典的值替换列表的值而不破坏列表层次结构。

Output should be like this: 输出应如下所示:

l = [[['da-1.txt', 'it-1.txt'], 'da-2.txt'], ['en-1.txt', 'en-2.txt], 'it-2.txt']

You could go over the list and for each element check if it's a list. 您可以遍历该列表,并检查每个元素是否为列表。 If it isn't, replace it with the corresponding element of the dictionary if it exists. 如果不是,请将其替换为字典中相应的元素(如果存在)。 If it is, apply the same algorithm recursively: 如果是这样,则递归应用相同的算法:

def rec_replace(l, d):
    for i in range(len(l)):
        if isinstance(l[i], list):
            rec_replace(l[i], d)
        else :
            l[i] = d.get(l[i], l[i])

Note: 注意:
This implementation is of an in-place replacement of the list's elements. 此实现是就地替换列表元素。 Alternatively, a similar approach could be used to return a new list instead. 或者,可以使用类似的方法来返回新列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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