python - 用空格分隔的文本在 python 中打印列表列表

标签 python linux list delimiter

我有:

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)))
  1. for 循环允许您在其自己的行中打印每个元组(还有其他方法,但我发现这种方法比其他方法更具可读性)。

  2. .join 连同理解(将元组内的 int 值转换为 str)格式化你的元组,这样每个值都用空格分隔。格式字符串中的 {0} 是一个占位符,指定它将被 .format() 调用的第一个(索引 0)参数替换。

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

关于python - 用空格分隔的文本在 python 中打印列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543738/

相关文章:

Python使用类似于模拟补丁的技术缓存内部调用

linux - 如何终止 webshel​​l 上的 ping?

java - jps 不工作

list - 列表替换中的 Prolog 元素

r - 如何获取列表中每个元素的最后一个子元素?

python - 将 QcomboBox 的默认值设置为空

Python安装报错 "A newer version of the Python launcher is already installed"

python - 如何减少 Python 绘图中的空白?

windows - 从忽略读取错误的光学介质恢复

Python 循环迭代,替换列表时间序列中的空值