我有:
surfaceList = [(21, 22, 2, 4, 24), (27, 28, 7, 4, 30)]
我要:
The vertex are 21 22 2 4 24
The vertex are 27 28 7 4 30
我用过
totalSurface = len(surfaceList)
print " total surface = %d " % (totalSurface)
for surfaceGenNew in range(totalSurface):
print " The vertex are " surfaceList[surfaceGenNew]
错误是:
print " The vertex are %s" surfaceInformationVertexList[surfaceGenNew]
^
Error: invalid syntax
我也用过
foo = [(21, 22, 2, 4, 24), (27, 28, 7, 4, 30)]
print " \n The vertex are ".join(foo)
错误是
TypeError: sequence item 0: expected string, tuple found
我可以使用困难的方法来查找单个列表的长度,然后对每个列表项使用 if 条件,然后打印相同的内容,但我相信会有聪明的方法来做到这一点。
有什么建议吗?
最佳答案
你有一个元组列表。尝试
for s in surfaceList:
print("The vertex are {0}".format(" ".join(str(x) for x in s)))
for
循环允许您在其自己的行中打印每个元组(还有其他方法,但我发现这种方法比其他方法更具可读性)。.join
连同理解(将元组内的int
值转换为str
)格式化你的元组,这样每个值都用空格分隔。格式字符串中的{0}
是一个占位符,指定它将被.format()
调用的第一个(索引 0)参数替换。.format()
连接文本(顶点是...)和空格分隔值。
关于python - 用空格分隔的文本在 python 中打印列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543738/