Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为什么列表中的一个元素没有被打印出来?_Python_List_Graph - Fatal编程技术网

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

Python:为什么列表中的一个元素没有被打印出来?,python,list,graph,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:

我试图打印图形中的不同节点,但给出了具有以下内容的边列表:

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

对我来说也很有用

一种可能更具python风格的形式,使用set:

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

当我看到您插入的文本时,看起来您将制表符和空格混合为左侧空白:

这可以通过查看每条线的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)
... 
... """

在我看来,
返回节点
行执行得太早了。将代码写入一个文件,并使用
python-tt
选项检查空白问题。

它为我打印
[1,2,3]
。使用python 2.7.3,我尝试了代码,效果很好
打印查找节点(图)
=>
[1,2,3]
此处相同:使用windows命令提示符…这可能相关吗?
节点应该是一个集合,而不是一个列表。仍然不打印最后的节点!。。我的循环似乎在第一个边缘后停止..不确定为什么如果使用windows提示符,可能是在输入enter之前?听起来很困惑…我正要添加这个作为答案…实际上return没有正确缩进…哦python…我很快就会习惯你:)你应该确保你使用的是一个python友好的编辑器,它使用四个空格标签进行缩进。其他任何事情都会让人头疼。。