Python返回空列表

2024-03-29 00:12:02 发布

您现在位置:Python中文网/ 问答频道 /正文

class Map():

    def returnWay(self, node1, node2):
        final_list = []
        temp_list = []
        self._returnWay(node1, node2, final_list, temp_list)
        return final_list

    def _returnWay(self, node1, node2, final_list, temp_list):
        if node1 not in temp_list:
            temp_list.append(node1)
            if node1 == node2:
                final_list.append(temp_list)
                del temp_list[-1]
            else:
                for x in node1.nexts():
                    self._returnWay(x, node2, final_list, temp_list)
                del temp_list[-1]


path = Map()

for x in path.returnWay(node1, node2):
    print x

好吧,伙计们,首先我不会说英语,所以如果我在说英语时犯了一些错误,请原谅。。。你知道吗

在这里,我试图获得两个节点之间的所有现有方式,其中有4个,但是我得到了4个空列表。你知道吗

如果我把第13行“for x in temp\u list:print x”放进去,它会打印所有4种方式,但由于某些原因,它不会将它们添加到最终的\u列表中。你知道吗


Tags: pathinselfmapforifdeftemp
1条回答
网友
1楼 · 发布于 2024-03-29 00:12:02

您的代码无法在我的计算机上运行,因为没有定义node1。你知道吗

但我想我发现了问题: 在Python中,如果将temp\u list附加到final\u list,那么对temp\u list所做的所有更改也将应用到final\u list。你知道吗

我在候机楼试过这个,看这里:

>>> a = ['a', 'b', 'c']
>>> e = 'd'
>>> a.append(e)
>>> a
['a', 'b', 'c', 'd']
>>> flist=[]
>>> flist.append(a)
>>> flist
[['a', 'b', 'c', 'd']]
>>> del a[-1]
>>> a
['a', 'b', 'c']
>>> flist
[['a', 'b', 'c']]

一个解决方案是创建一个完整的列表副本并将其放入最终列表中。如何动态创建完整列表副本?临时列表[:]所以我的解决方案是:

class Map():

    def returnWay(self, node1, node2):
        final_list = []
        temp_list = []
        self._returnWay(node1, node2, final_list, temp_list)
        return final_list

    def _returnWay(self, node1, node2, final_list, temp_list):
        if node1 not in temp_list:
            temp_list.append(node1)
            if node1 == node2:
                final_list.append(temp_list[:])
                del temp_list[-1]
            else:
                for x in node1.nexts():
                    self._returnWay(x, node2, final_list, temp_list[:])
                del temp_list[-1]


path = Map()

for x in path.returnWay(node1, node2):
    print x

所以我希望这能像你想的那样起作用。你知道吗

相关问题 更多 >