【问题标题】:printing list of lists in python with space delimited text用空格分隔文本在python中打印列表列表
【发布时间】:2016-04-11 08:39:48
【问题描述】:

我有:

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

有什么建议吗?

【问题讨论】:

    标签: python linux list delimiter


    【解决方案1】:

    你有一个元组列表。试试

    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() 连接文本(顶点是...)和空格分隔的值。

    【讨论】:

    • 给出错误:TypeError: sequence item 0: expected string, int found
    • 它工作正常,你能解释两件事吗? 1:在这种情况下分隔如何工作以及{0}如何工作,它将帮助我将来自己使用它.. 2:你怎么这么快得到 +3 :) 因为我这么快得到 -1!
    • @HamadHassan 当然,刚刚添加了有关所用方法的额外信息。不完全确定您为什么被否决,因为这是一个有效且热门的问题。
    • 我感谢您的时间和解释,因为它是一个单一的班轮,我是初学者,我把它弄坏了。你能告诉我我哪里弄错了吗? for s in surfaceList: for x in s: print("顶点是{0}".format(" ".join((str(x)))))
    • 当您在嵌套的 for 循环中时,您已经从元组中获取了单个元素,并且 join() 只能在一系列字符串上完成。试试这个: for s in surfaceList: print_string = "The vertex are " for x in s: print_string += str(x) + " " print print_string[:-1]
    【解决方案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(",","")
    

    但我强烈建议使用@selcuk 的回答

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      相关资源
      最近更新 更多