简体   繁体   中英

Printing a list in rows of a set length (Python)

I'm fairly new to Python and having a hard time figuring out how to print a list in rows given these circumstances:

The list starts out empty and the computer generates random 2-digit integer entries, which are then appended to the list. Printing the list is easy enough, either in a single column or in a single line using

for i in list:
    print(i, end = "")

but what I want to do is print in rows of 4, ending the list with whatever the remainder is (eg a row of 3), so that the outcome would look something like this:

81  27  19  55
99  45  32  90
67  83  20  72
12  86  21

What is the best and most straightforward way to do this?

Edit: I forgot to clarify that I'm working in Python 3. Sorry about that.

There many ways to do this, as others have shown. One more:

for i in range(0, len(mylist), 4):
    print(*mylist[i:i+4], sep=' ')

You could use the modulus operator to recognize when you're on the 4th column and change the end value to print .

for i, val in enumerate(list):
    end = '\n' if (i + 1) % 4 == 0 else '  '
    print(val, end=end)

Just add a statement to drop in a newline every 4th item:

count = 1
for i in list:
    print(i, end = "")
    count += 1
    if count % 4 == 0:
        print('\n')

If you like indexing better:

for i in len(list):
    print(list[i], end = "")
    if i % 4 == 0:
        print('\n')

Does that solve the problem for you?

for ind, val in enumerate(yourList):
    if ind != 0 and ind % 4 == 0:
        print('\n')
    print(val, end=' ')

If this is your starting list of numbers:

numbers = [81, 27, 19, 55, 99, 45, 32, 90, 67, 83, 20, 72, 12, 86, 21]

I would first group them into separate lists:

grouped_numbers = [numbers[i:i+4] for i in range(0,len(numbers),4)]

Then I would print out each group with a blank space in between them using the join function

for group_of_numbers in grouped_numbers:
    print (" ".join(map(str,group_of_numbers)))

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