生成一个 while 循环

huangapple go评论61阅读模式
英文:

Generate a while loop

问题

我正在尝试为我的代码创建一个while循环我的想法是不要使用太多的for循环来将其放入一个函数中

int_list = [[[1]],2,[[[[3]]]]]

for i in int_list:
    if type(i) != list:
        list_of_lists.append(i)
    else:
        for a in i:
            if type(a) != list:
                list_of_lists.append(a)
            else:
                for j in a:
                    if type(j) != list:
                        list_of_lists.append(j)
                    else:
                        for h in j:
                            if type(h) != list:
                                list_of_lists.append(h)
                            else:
                                for r in h:
                                    if type(r) != list:
                                        list_of_lists.append(r)

期望的输出

list_of_lists = [1,2,3]

英文:

I'm trying to create a while loop for my code. The idea is not to use so many "for" loops to put it into a function

int_list = [[[1]],2,[[[[3]]]]]

for i in int_list:
    if type(i) != list:
        list_of_lists.append(i)
    else:
        for a in i:
            if type(a) != list:
                list_of_lists.append(a)
            else:
                for j in a:
                    if type(j) != list:
                        list_of_lists.append(j)
                    else:
                        for h in j:
                            if type(h) != list:
                                list_of_lists.append(h)
                            else:
                                for r in h:
                                    if type(r) != list:
                                        list_of_lists.append(r)

Expected Output

list_of_lists = [1,2,3]

答案1

得分: 0

一种减少for循环的方法是创建一个递归函数

该函数通过将sublist(i)作为参数传递给helper(),递归调用自身。然后使用extend()方法将生成的列表扩展到结果列表中。

如果它的instance不是list,则执行else部分。将值附加lis中。

代码:

def helper(lis):
    res = []
    for i in lis:
        if isinstance(i, list):
            res.extend(helper(i))
        else:
            res.append(i)
    return res

int_list = [[[1]], 2, [[[[3]]]]
list_of_lists = helper(int_list)
print(list_of_lists)

输出:

[1, 2, 3]
英文:

One way to reduce for loop is to create a recursive function.

The function recursively calls itself on that sublist(i) by passing it as an argument to helper(). The resulting list is then extended to the result list using the extend() method.

If it's instance is not a list. it runs else part. appending value into the lis

Code:

def helper(lis):
    res=[]
    for i in lis:
        if isinstance(i, list):
            res.extend(helper(i))
        else:
            res.append(i)
    return res

int_list=[[[1]], 2, [[[[3]]]]]
list_of_lists=helper(int_list)
print(list_of_lists)

Output:

[1,2,3]

答案2

得分: 0

递归函数是展平这样的列表的理想方式。如果您真的想在单个 while 循环中执行此操作,那么可以通过创建一个堆栈来帮助您跟踪每个子列表中的位置。

这在您定义和调用递归函数时会自动发生;每次调用函数都会将函数的所有本地变量放入一个“堆栈”中,就像下面的代码在发现新的子列表时每次都将当前列表和索引放入名为 stack 的列表中一样。

int_list = [[[1]],2,[[[[3]]]]

flat_list = []
stack = []
i = 0
while True:
    if i >= len(int_list):
        # 我们已经到达这个子列表的末尾,
        # 因此返回堆栈以继续之前的位置。
        if not stack:
            break  # 全部完成!
        int_list, i = stack.pop()
    elif isinstance(int_list[i], list):
        # 跟踪当前列表和要查看的下一个项目,
        # 然后开始查看这个子列表。
        stack.append((int_list, i+1))
        int_list, i = int_list[i], 0
    else:
        # 我们找到了一个标量项!将其添加到平坦列表中。
        flat_list.append(int_list[i])
        i += 1

assert flat_list == [1, 2, 3]
英文:

A recursive function is the ideal way to flatten a list like this. If you really want to do it in a single while loop, though, it is possible, by creating a stack to help you keep track of where you are in each sublist.

This happens automatically for you when you define and call a recursive function; every call to the function puts all the function's local variables onto a "stack", just like the code below puts the current list and index onto a list called stack every time a new sublist is discovered.

int_list = [[[1]],2,[[[[3]]]]]

flat_list = []
stack = []
i = 0
while True:
    if i >= len(int_list):
        # We're at the end of this sublist,
        # so go back to the stack to pick up where we left off.
        if not stack:
            break  # all done!
        int_list, i = stack.pop()
    elif isinstance(int_list[i], list):
        # Keep track of the current list and the next item
        # for us to look at, and then start looking at this sublist.
        stack.append((int_list, i+1))
        int_list, i = int_list[i], 0
    else:
        # We found a scalar item!  Add it to the flat list.
        flat_list.append(int_list[i])
        i += 1

assert flat_list == [1, 2, 3]

huangapple
  • 本文由 发表于 2023年2月18日 11:43:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定