繁体   English   中英

用Python编辑输出

[英]Editing output in Python

我有以下代码:

nodeCount = 10
vertexCount = 15

vertices = {}
while len(vertices) < vertexCount:
    x = random.randint (1, nodeCount)
    y = random.randint (1, nodeCount)
    if x == y: continue
    if y < x: x, y = y, x
    w = random.randint(0,10)
    vertices [x, y] = w

print (nodeCount, vertexCount)
for (x, y), w in vertices.items ():
    print (x, y, w)

运行此命令时,我得到的输出类似于以下内容:

(10, 15)
(3, 8, 10)
(6, 8, 1)
(4, 10, 7) #there's more output but not necessary to post

我正在尝试将输出格式设置为以下格式,但是在输出中没有括号或逗号的情况下,我可以将其输出到正在处理的其他内容中:

10 15
3 8 10
6 8 1
4 10 7

我已经读过有关使用.split()的信息,但是我通常不使用Python,并且在尝试更改输出格式的方式时遇到了问题。

在Python 2中, print是一个语句,而不是方法,因此在不带括号的情况下调用它:

print nodeCount, vertexCount
...
print x, y, w

如果使用括号将其调用,则将创建一个tuple print打印一个元组时,它会将内容包装在括号内,因为那是tuple表示形式。

在Python 2.x中, print 不是一个函数(它是一个statement ),所以您在这一行中正在做什么:

print (x, y, w)

是您将x, y and w包装在一个tuple中并进行打印。 因此,输出将是一个tuple

你能做什么?

只需删除括号()

print x, y, w

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM