如何在保持列表层次结构的同时在嵌套列表中连接字符串? [英] How to join strings in nested lists while maintaining list hierarchy?

查看:41
本文介绍了如何在保持列表层次结构的同时在嵌套列表中连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个清单:

[a"、b"、[c"、[d"、e"]、f"]]

我希望在保持列表结构的同时将每个列表中的字符串元素连接在一起.

预期的行为是这样的:

<预><代码>>>>test_list = [a"、b"、[c"、[d"、e"]、f"]]>>>功能(测试列表)[ab"、[c"、[de"]、f"]]

它非常类似于

I have this list:

["a", "b", ["c", ["d", "e"], "f"]]

I wish to join the string elements in each list together while maintaining the list structure.

The expected behaviour is something like this:

>>> test_list = ["a", "b", ["c", ["d", "e"], "f"]]
>>> function(test_list)
["ab", ["c", ["de"], "f"]]

It would be very similar to this, but it must able to handle an arbitrary number of nested lists.

I have tried to solve it using a recursive function but was not able to get the expected outcome.

Any tips?

解决方案

You were right to try to use recursion to solve the problem. Here is how I designed my function:

sample = ["a", "b", ["c", ["d", "e"], "f"]]
desired = ["ab", ["c", ["de"], "f"]]


def mergeList(array):
    ret = []    #final array
    newEl = ""  #merged element

    for el in array:
        #If the element is a list, add our merged element and then
        #call the mergeList function on our list
        if type(el) == list:
            ret.append(newEl)
            newEl = ""  #clear the merged element so we can start over
            ret.append(mergeList(el))
        else:
            newEl += str(el)    #Add to the merged element

    #Final merge
    if newEl != "":
        ret.append(newEl)

    return ret

print(mergeList(sample))

The mergedList function will try to combine elements one by one until it reaches a list. When it finally reaches a list, it will first store the combined element to a new list and then repeat the process with the new list and store that result. After processing, it continues.

I made a crude diagram that I think can explain this. Each level represents a new recursive call on a smaller list. The bolded letters represent the variable newEl which contains the string that accumulates each element.

这篇关于如何在保持列表层次结构的同时在嵌套列表中连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆