python - 一次使用多个输入

标签 python python-3.x

现在我的程序接受输入并给出单行输出。这个程序基本上使用一个名为 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 对象。它什么也没做。

关于python - 一次使用多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33234663/

相关文章:

python - 在 groupby 循环中编号和创建数据帧

python - 如何使用带有 Python 的 Selenium WebDriver 获取选定的选项?

python3 os.rename() 不会重命名名称中包含单词 'Copy' 的文件

python - 执行用 yaml 编写的带有变量的 python 脚本

python-3.x - 如何使用Socket库使用python3连接到ipv6主机

python - Visual Studio 2017无法在python文件中创建书签?

python - 在命令行中将文件名传递给 python 脚本

python - 我们可以在序列化器字段中填写我不需要的字段吗?

python - Groupby 类和计数特征中的缺失值

python - 在 Python 上解码 HTML 实体