【问题标题】:How to loop a list and append it to a dictionary in a loop?如何循环列表并将其附加到循环中的字典?
【发布时间】:2017-05-30 01:17:35
【问题描述】:

适用于动态环形拓扑项目。具体来说,我需要为每个节点命名:s1,s2...sz,并将每个主机命名为 h1-1,h1-2,...hz-n。所以z是节点的数量,n是连接到每个节点的主机的数量。所以我有一个节点列表,我试图使用节点作为键来拥有另一个主机列表,然后我可以将它们放入字典中以供使用。我怎样才能实现这个目标?示例图如下:

【问题讨论】:

  • 你尝试过做什么?展示你的代码并解释你到底在哪里挣扎。 (还有你为什么要放一个“node.js”标签?)
  • 我正在尝试构建动态 Mininet 拓扑。所以我在下面发布了代码。
  • 我的代码太长了...我先试试下面的解决方案...谢谢...

标签: python dictionary topology


【解决方案1】:

我认为您正在寻找类似以下内容的东西:

# run with python dynamictopo.py z n
# e.g.: python dynamictopo.py 3 2
import sys

z = int(sys.argv[1])  # number of nodes
n = int(sys.argv[2])  # number of hosts

nodes = []
for i in range(0, z):
    nodes.append("s" + str(i + 1))

print(nodes)

dct = {}
for j, node in enumerate(nodes):
    hosts = []
    for h in range(0, n):
        hosts.append("h" + nodes[j][1] + "-" + str(h + 1))
    dct[node] = hosts

print(dct)

这将打印 ['s1', 's2', 's3'] 和 {'s2': ['h2-1', 'h2-2'], 's3': ['h3-1', 'h3-2'], 's1': ['h1-1', 'h1-2']} 如果你使用 3 和 2 作为命令行参数。请注意,dictionaries 是无序的。

或者使用这个:

# run with python dynamictopo.py z n
# e.g.: python dynamictopo.py 3 2
import sys

z = int(sys.argv[1])  # number of nodes
n = int(sys.argv[2])  # number of hosts

dct = {}
for i in range(z):
    hosts = []
    for h in range(0, n):
        hosts.append("h" + str(i + 1) + "-" + str(h + 1))
    dct["s" + str(i + 1)] = hosts

print(dct)

【讨论】:

  • 非常感谢您的帮助!
  • 没问题。由于您是新来的:您可能想选择我的答案而不是评论。
  • 只是跟进,我遇到了一个语法错误,如下...你知道原因吗? dct = {} ^ SyntaxError: 无效语法
  • 哦,我复制了错误注释。所以^低于dct。如果我运行上面的代码,它会完美运行。仅当我将其应用于我的项目时才会发生错误....
猜你喜欢
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2018-12-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多