简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM