[英]How to print X items in a list per line
Given a list of strings I want to be able to print 4 items of that list per line with one space between them until the list is exhausted.给定一个字符串列表,我希望能够每行打印该列表的 4 个项目,它们之间有一个空格,直到列表用完。 Any ideas?
有任何想法吗? Thanks
谢谢
Example:例子:
ListA = ['1', '2', '3', '4', '5', '6']
Given this list I would like my output to be:鉴于此列表,我希望我的输出是:
1 2 3 4
5 6
You can do that as follows:你可以这样做:
for i,item in enumerate(listA):
if (i+1)%4 == 0:
print(item)
else:
print(item,end=' ')
Another approach is something like this:另一种方法是这样的:
ListA = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13']
k = 0
group = ''
for i in ListA:
if k < 4:
group += i + ' '
k += 1
else:
group += '\n' + i + ' '
k = 1
print(group)
Alternatively, one can split the given list to chunks beforehand.或者,可以预先将给定的列表拆分为块。 See How do you split a list into evenly sized chunks?
请参阅如何将列表拆分为大小均匀的块? for various approaches:
对于各种方法:
my_list = ['1', '2', '3', '4', '5', '6']
n = 4
chunks = (my_list[i:i+n] for i in range(0, len(my_list), n))
for chunk in chunks:
print(*chunk)
# 1 2 3 4
# 5 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.