Skip to main content
 首页 » 编程设计

python之一次使用多个输入

2025年05月04日14hnrainll

现在我的程序接受输入并给出单行输出。这个程序基本上使用一个名为 network-x 的手动安装的 python 库(它创建和分析图形并具有许多内置的图论相关函数)。

对于这个特定的程序,它需要如下所示的输入:

6       <-- Order of the graph (i.e the graph has 0 to 5 vertices) 
1 2 3   <-- vertices going out from 0 
2       <-- vertices going out from 1 
3 5     <-- vertices going out from 2 
4       <-- vertices going out from 3 
5       <-- vertices going out from 4 
        <-- vertices going out from 5 (no vertices going out from 5) 

并返回输出(说明图中有多少连通分量):

1 

另一个输入示例:

6 
3 5 
2 
 
4 
 
4 

和输出:

2 

我的程序的源代码是:

import networkx as nx 
import sys 
def main():      
 dag = nx.Graph() 
 order = int(input()) 
 for i in range (order): 
      dag.add_node(i) 
 for j in range(order): 
      seq = [input()] 
      for vertex in seq: 
           vertexList = vertex.split() 
           for element in vertexList: 
                dag.add_edge(j,int(element)) 
      j+=1 
 
 components = nx.number_connected_components(dag) 
 print (components) 
main() 

我目前正在思考如何让程序同时接受这两个输入并计算 2 行输出(每行输出每个输入的结果),如下所示:

6 
1 2 3 
2 
3 5 
4 
5 
 
6 
3 5  
2 
 
4 
 
4 
0 <-- when the the user inputs a zero, the loop terminates 

循环结束后输出:

1 
2 

如有任何帮助,我们将不胜感激。 P.S.如果你想安装 network-x 库,请访问 network-x 的 github 网站:https://networkx.github.io/documentation/latest/install.html

请您参考如下方法:

简单地使用一个循环并将每个结果保存在一个列表中:

def main(): 
    result = [] 
 
    while 1: 
        dag = nx.Graph() 
        order = int(input()) 
        if not order: # check if it's 0 
            break # end the loop 
        for i in range (order): 
            dag.add_node(i) 
        for j in range(order): 
            vertexList = input().split() # no need to put this single string into a list 
            for element in vertexList: 
                dag.add_edge(j,int(element)) 
        result.append(nx.number_connected_components(dag)) 
 
    print (result) 

我删除了不必要的 [input()],它生成了一个可以循环的单元素 list。无需循环访问单个对象。我还使用 j 删除了循环末尾的 j += 1,因为所做的只是在它从 获取下一个值之前重新分配一个新值code>range 对象。它什么也没做。