[英]Python: print data to new line after printing some data
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)
For example if i have a data like例如,如果我有一个像
bob,sob,cob,dab
if i print it using loop then it will be printed one by one what i want is after printing bob and sob i want the cursor come back upwards and then print 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
if i remove dab in the above data then the output should be如果我在上面的数据中删除 dab 那么输出应该是
bob cob鲍勃
sob哭泣
Is this possible in Python?这在 Python 中可能吗? can anyone provide an example
谁能提供一个例子
You can do 你可以做
data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
for row in zip(*data):
print(' '.join(row))
output 产量
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
EDIT - expand the answer in case of unequal length: Use itertools.zip_longest()
编辑-在长度不相等的情况下扩展答案:使用
itertools.zip_longest()
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))
output 产量
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David
The default fillvalue is None
- you can keep it if you prefer 默认填充值是“
None
-如果愿意,可以保留它
Expanding on one of the answers and using your simple list (bob, sob, cob, dab), you can use a modulo based on index position in the single-dimension list, then append '\\n' to create a new line with proper spacing: 扩展答案之一并使用简单列表(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]))
Output: 输出:
bob sob
cob dab
https://docs.python.org/3/library/functions.html#print https://docs.python.org/3/library/functions.html#print
data = ["Mom", "Dad", "Son", "Daughter"]
for person in data:
print(person, end='\n')
If what I think you're trying to do is just get a statement to print on a new line, the end=
parameter must be added into the print statement. 如果我认为您要尝试执行的操作只是在新行中打印一条语句,则必须在print语句中添加
end=
参数。 It's not required, but it is useful. 它不是必需的,但很有用。
If you want to print multiple names on the same line, you can use the separator parameter sep=","
to add a comma after each name. 如果要在同一行上打印多个名称,则可以使用分隔符参数
sep=","
在每个名称后添加逗号。 The end
parameter goes after it to ensure skipping to the next line. end
参数位于其后,以确保跳至下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.