简体   繁体   English

如何使用嵌套 for 循环创建嵌套列表?

[英]How to Create a nested list using nested for loop?

    def remove_extras(self, paths, destination):
        # Delete all paths that does not include the destination
        destination_paths = []
        destination_path = []
        for path in paths:
            if destination in path:
                for router in path:
                    destination_path.append(router)
                destination_paths.append(destination_path)
        print(destination_paths)

        return destination_paths[1:]

why am I getting [[router, router, router, ....]] and not [[router, router, ...], [router, router, ...], .....]?为什么我得到 [[router, router, router, ....]] 而不是 [[router, router, ...], [router, router, ...], .....]?

I think you overlooked that you are appending routers to the same destination_path list object all the time - then after the inner for-loop you are appending the same destination_path list object multiple times to destination_paths .我认为您忽略了您一直将路由器附加到相同的destination_path列表 object - 然后在内部 for 循环之后,您将相同的destination_path列表 object 多次附加到destination_paths

Instead, you should move the definition of destination_path inside the outer for loop - the code would then look like this:相反,您应该将destination_path的定义移到外部for循环中 - 代码将如下所示:

    def remove_extras(self, paths, destination):
        # Delete all paths that does not include the destination
        destination_paths = []
        for path in paths:
            if destination in path:
                destination_path = []
                for router in path:
                    destination_path.append(router)
                destination_paths.append(destination_path)
        print(destination_paths)

        return destination_paths[1:]

Without even knowing what you would like to achieve, the previous posted code was almost right.甚至不知道你想要实现什么,之前发布的代码几乎是正确的。 Try this one here:在这里试试这个:

def remove_extras(self, paths, destination):
    destination_paths = []
    for path in paths:
        destination_path = []
        if destination in path:
            for router in path:
                destination_path.append(router)
    
        destination_paths.append(destination_path)
    
    return destination_paths

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM