使用空格分隔tex打印python中的列表列表

2024-10-03 19:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有:

surfaceList = [(21, 22, 2, 4, 24), (27, 28, 7, 4, 30)]

我想要:

^{pr2}$

我用过

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条件,然后打印相同的内容,但我相信有一种聪明的方法可以做到这一点。在

有什么建议吗?在


Tags: the方法列表lenfoo错误surfaceare
2条回答

修正了你的写作方式:

surfaceList = [(21, 22, 2, 4, 24), (27, 28, 7, 4, 30)]
totalSurface = len(surfaceList)

print " total surface = %d " % (totalSurface)

for surfaceGenNew  in range(totalSurface):
    print " The vertex are  " + str(surfaceList[surfaceGenNew])[1:-1].replace(",","")

但我强烈建议你接受“塞尔库克”的回答

你有一个元组列表。试试看

for s in surfaceList:
    print("The vertex are {0}".format(" ".join(str(x) for x in s)))
  1. for循环允许您在每个元组的行中打印每个元组(还有其他方法,但我发现这个方法比其他方法更可读)。

  2. .join和理解(将元组中的int值转换为str)格式化元组,使每个值都用空格隔开。格式字符串中的{0}是一个placeholde,它指定它将被.format()调用的第一个(索引0)参数替换。

  3. .format()连接文本(顶点是…)和空格分隔的值。

相关问题 更多 >