如何将项目递归添加到列表?
当前,我正在研究一个问题.给了我一个列表,该列表的元素可以包含其他列表,列表列表或整数.例如,我可能会收到:
Currently, I'm working on a problem. I am given a list, whose elements may contain other lists, lists of lists, or integers. For example, I may receive:
[[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]]
我的目标是解析数组,并将仅整数附加到新列表中.到目前为止,这是我所做的:
My goal is to parse the array, and append only the integers to a new list. Here is what I have done so far:
def fun(a):
if a == []:
return None
elif type(a) == int:
print("Found a digit: ", a)
return a
for i in a:
fun(i)
当前,此函数递归地遍历列表并成功找到每个整数;现在,我在将这些整数追加到新列表中并在最后返回该列表时遇到了问题.输出应该是这样的:
Currently, this function recursively goes through the list and successfully finds each integer; now, I am having an issue with appending those integers to a new list, and returning that list at the very end. The output should be like this:
[1,2,3,4,5,6,7,9]
有指针吗?
将要附加的列表作为参数传递.
Pass the list to append to as a parameter.
def fun(a, result):
if type(a) == int:
print("Found a digit: ", a)
result.append(a)
else:
for i in a:
fun(i, result)
old_list = [[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]]
new_list = []
fun(old_list, new_list)
print(new_list)
如果需要原始功能签名,可以将其分为两个功能.
If you need the original function signature, you can split this into two functions.
def fun(a):
result = []
fun_recursive(a, result)
return result
fun_recursive()
的定义如上.