Python 如何格式化要打印的列表?

Python 如何格式化要打印的列表?,python,list,printing,format,Python,List,Printing,Format,如何格式化要打印的python列表 例如: list = ['Name1 ', Price1, Piece1, 'Name2 ', Price2, Piece2, 'Name3', Price3, Piece3] 我希望对列表进行格式化,使其打印如下: Name1 价格1-件1 姓名2 价格2-件2 名字3 价格3-件3 如果您认为Price1和Price2是字符串(您忘记了'符号) 一个解决方案: lst = ['Name1 ', 'Price1', 'Piece1', 'N

如何格式化要打印的python列表

例如:

list = ['Name1 ', Price1, Piece1, 'Name2 ', Price2, Piece2, 'Name3', Price3,
        Piece3]
我希望对列表进行格式化,使其打印如下:

Name1
价格1-件1
姓名2
价格2-件2
名字3
价格3-件3

如果您认为
Price1
Price2
是字符串(您忘记了
'
符号)

一个解决方案:

lst = ['Name1 ', 'Price1', 'Piece1', 'Name2 ', 'Price2', 'Piece2', 'Name3', 'Price3', 'Piece3']

for i in xrange(0, len(lst), 3):
    print(lst[i] + "\n" + lst[i+1] + " - " + lst[i+2])
返回:

Name1 
Price1 - Piece1
Name2 
Price2 - Piece2
Name3
Price3 - Piece3
另外,永远不要命名变量
list
list是python中已经使用过的关键字

另一个丑陋的解决方案:

lst = ['Name1 ', 'Price1', 'Piece1', 'Name2 ', 'Price2', 'Piece2', 'Name3', 'Price3', 'Piece3']

for i in xrange(0, len(lst), 3):
    print(lst[i] + "\n" + lst[i+1] + " - " + lst[i+2])
print(“\n”).join([lst[i]+“\n”+lst[i+1]+“-”+lst[i+2]表示范围(0,len(lst),3)])
输出

Name1 
1-2
Name2 
1-2
Name3
2-1

然后你想用这些碎片做什么就做什么。

我要做的就是这样

print(*['{}\n{} - {}'.format(*lst[i:i + 3]) for i in range(0, len(lst), 3)], sep='\n')
#Declare some variables for example
Price1 , Price2 , Price3 = 12 , 57 , 33
Piece1 , Piece2 , Piece3 = 5 , 4 , 2

#Create a two-dimensional array for more clear code
li = [['Name1', Price1 , Piece1] , ['Name2 ', Price2, Piece2] , ['Name3', Price3, Piece3]]

#Itterate through the array and print 
for i in range(len(li)) :
    print "\n"
    for y in range(len(li[i])) :
        if y == 0 :
            print li[i][0] 
        else:
            print li[i][1] , " , " , li[i][2] 

当然,它可以更加完善和高效。如果您有任何问题,我希望我能帮助您。

Price1
Price2
是对象还是什么?Price1,Price2,Price3,Piece1,Piece2,Piece3是数字这是python 3.x还是2.x?这是python 2.xIt似乎您的应用程序需要逻辑分组(名称,价格,piece),那么,维护元组列表是否有意义呢?您也可以迭代该列表并根据所需格式打印每个元组。此解决方案缺少Pricex和PieceX之间的破折号。只需使用xrange或Range即可。此代码片段可以解决此问题,真正有助于提高您的文章质量。请记住,您将在将来为读者回答这个问题,而这些人可能不知道您的代码建议的原因。请使用链接解释此代码的工作原理,而不要只是给出代码,因为解释更有可能帮助未来的读者。另见。
ls = ['Name1 ', 'Price1', 'Piece1', 'Name2 ', 'Price2', 'Piece2', 'Name3', 'Price3', 'Piece3']

for i in range(0, len(ls), 3):
    print(*( ls[i:i + 3]))
#Declare some variables for example
Price1 , Price2 , Price3 = 12 , 57 , 33
Piece1 , Piece2 , Piece3 = 5 , 4 , 2

#Create a two-dimensional array for more clear code
li = [['Name1', Price1 , Piece1] , ['Name2 ', Price2, Piece2] , ['Name3', Price3, Piece3]]

#Itterate through the array and print 
for i in range(len(li)) :
    print "\n"
    for y in range(len(li[i])) :
        if y == 0 :
            print li[i][0] 
        else:
            print li[i][1] , " , " , li[i][2]