我在使用 python 递归展平列表时遇到问题.我已经看到了许多需要列表理解的方法和需要导入的各种方法,但是我正在寻找一种非常基本的方法来递归展平不使用任何 for 循环的不同深度的列表.我进行了一系列测试,但有两个我无法通过I am having trouble using python to recursively flatten a list. I have seen a number of methods that require list comprehension and various methods requiring imports however I am looking for a very basic method to recursively flatten a list of varying depth that does not use any for loops either.I had a series of test however there are two I cannot passflatten([[[[]]], [], [[]], [[], []]]) # empty multidimensional listflatten([[1], [2, 3], [4, [5, [6, [7, [8]]]]]]) # multiple nested list我的代码def flatten(test_list): #define base case to exit recursive method if len(test_list) == 0: return [] elif isinstance(test_list,list) and type(test_list[0]) in [int,str]: return [test_list[0]] + flatten(test_list[1:]) elif isinstance(test_list,list) and isinstance(test_list[0],list): return test_list[0] + flatten(test_list[1:]) else: return flatten(test_list[1:])我希望得到一些建议.推荐答案这可以处理你的两种情况,我认为可以解决一般情况,没有任何 for 循环:This handles both of your cases, and I think will solve the general case, without any for loops:def flatten(S): if S == []: return S if isinstance(S[0], list): return flatten(S[0]) + flatten(S[1:]) return S[:1] + flatten(S[1:]) 这篇关于递归地展平列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-29 02:29