【递归】把不规则列表里面的非字符串元素去掉

一、题目描述

把不规则列表里面的非字符串元素去掉,其中输入和输出如下测试用例所示:

Input = ["a", "b", ["c"], [[], "d"], [[[[["e"], "f"], "g"], "h"], "i"], "j"]
Output = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

二、代码实现

递归基础题。
递归边界:遇到字符串就将当前元素添加到答案列表;
递归函数:遇到列表就将该列表递归,注意是要遍历该列表,对此列表每个元素进行递归!

'''    
把不规则列表里面的非字符串元素去掉;
Input = ["a", "b", ["c"], [[], "d"], [[[[["e"], "f"], "g"], "h"], "i"], "j"]
Output = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
'''
input  = ["a", "b", ["c"], [[], "d"], [[[[["e"], "f"], "g"], "h"], "i"], "j"]
ans = []
temp = ''
# 递归
def fun(str1):
    if (type(str1) == str):
        ans.append(str1)
    elif type(str1) == list:
        # 注意循环列表中的每个元素递归,而不是直接fun(str1)
        for j in range(len(str1)):
            fun(str1[j])


for i in range(len(input)):
    fun(input[i])
print(ans)
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

猜你喜欢

转载自blog.csdn.net/qq_35812205/article/details/128583425