Python:在打印一些数据之后将数据打印到新行

2024-06-16 10:03:58 发布

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

def printable(l):
    for i in range(len(l)):
        for j in range(len(l[i])):
            print(l[i][j])
        print()
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printable(tableData)

例如,如果我有一个数据

bob,sob,cob,dab 

如果我打印它使用循环,然后它将被打印一个接一个我想要的是 打印完bob和sob后,我希望光标回到上方,然后打印cob-dab

first:print  
      bob  
      sob  
second:then cursor comes back up and print  
      cob  
      dab              
the output i wanted is  
bob cob  
sob dab  

如果删除上述数据中的dab,则输出应为
鲍勃·科布
呜咽
这在Python中是可能的吗? 有人能举个例子吗


Tags: 数据inforlendefrangebobprint
2条回答

你能做到的

data = [['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

for row in zip(*data):
    print(' '.join(row))

输出

apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose

编辑-长度不等时展开答案: 使用^{}

from itertools import zip_longest
data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose']]

for row in zip_longest(*data, fillvalue=''):
    print(' '.join(row))

输出

apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David

默认的fillvalue是None——如果您愿意,可以保留它

展开其中一个答案并使用简单列表(bob、sob、cob、dab),可以使用基于一维列表中索引位置的模,然后附加“\n”以创建具有适当间距的新行:

data = ['bob','sob','cob','dab']
print(' '.join(['\n{}'.format(i) if data.index(i) % 2 == 0 else i for i in data]))

输出:

bob sob 
cob dab

相关问题 更多 >