Python:为什么这个列表中的一个元素没有打印?

时间:2012-07-15 19:34:37

标签: python list graph

我在给定带有以下内容的边列表时尝试在图形中打印不同的节点:

def find_nodes(graph):
    # get the distinct nodes from the edges
    nodes = []
    l = len(graph)
    for i in range(l):
        edge = graph[i]
        n1 = edge[0]
        n2 = edge[1]
        if n1 not in nodes:
            nodes.append(n1)
        if n2 not in nodes:
            nodes.append(n2)
    return nodes

graph = ((1,2),(2,3), (3,1))
print find_nodes(graph)

但我只得到(1,2)我如何错过3

2 个答案:

答案 0 :(得分:2)

当我查看您插入的文字时,看起来您将标签和空格混合为左手空白:

这可以通过查看每行的repr来确认:

'    def find_nodes(graph):'
'        # get the distinct nodes from the edges'
'        nodes = []'
'        l = len(graph)'
'        for i in range(l):'
'        \tedge = graph[i]'
'        \tn1 = edge[0]'
'        \tn2 = edge[1]'
'        \tif n1 not in nodes:'
'        \t\tnodes.append(n1)'
'        \tif n2 not in nodes:'
'        \t\tnodes.append(n2)'
'    \treturn nodes'

这可能导致线条没有缩进到您认为的水平。这是我将您的输入复制并粘贴到控制台后得到的结果:

>>> s = """
...     def find_nodes(graph):
...         # get the distinct nodes from the edges
...         nodes = []
...         l = len(graph)
...         for i in range(l):
...             edge = graph[i]
...             n1 = edge[0]
...             n2 = edge[1]
...             if n1 not in nodes:
...                     nodes.append(n1)
...             if n2 not in nodes:
...                     nodes.append(n2)
...             return nodes
...     
...     graph = ((1,2),(2,3), (3,1))
...     print find_nodes(graph)
... 
... """

我认为return nodes行过早执行。将代码写入文件并使用python -tt选项检查空白问题。

答案 1 :(得分:0)

也适合我。

可能更加pythonic的形式,使用set:

def find_nodes(graph):
    return list({element
                 for edge in graph
                 for element in edge})