简体   繁体   中英

python printing list items incremented on lines

I am trying to take a user input and print out a list of numbers in a box format onto different lines in python.

right now i have:

horizontalsize =  int (input ('please enter horizontal size '))

verticalsize = int (input ('please enter vertical size '))

numbers = horizontalsize * verticalsize

mylist = []

mylist.append(range(1,numbers))

for i in range(1,numbers,horizontalsize):

    print (i)

The user will input a height and width and if the height input is 5 and the width input is 3 it should print:

1 2 3

4 5 6

7 8 9

10 11 12

13 14 15

right now im currently getting:

1

4

7

10

13

How can i get the rest of the numbers to fill in? Any help is greatly appreciated!

This should work:

for i in range(1, numbers, horizontalsize):
    lst = range(i, i+horizontalsize)
    print lst  # format is [1,2,3]
    print ' '.join(map(str,lst))  # format is "1 2 3"

You can also declare a 2D list by list comprehension, example:

>>> horizontalsize = 3
>>> numbers = 15
>>> ll = [[x for x in range(y,y+horizontalsize)] 
for y in range(1,numbers,horizontalsize)]
>>> ll
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]
>>> for line in ll:
...    print ' '.join(map(str,line))
... 
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15

The range() you are using will start at 1, go up to numbers , and increase by horizontalsize each time. You are pulling your values for i directly from that range, so those will be the only values you get. One simple solution is to add a second, nested loop to generate the missing values (between i and i+horizontalsize ).

for i in range(1,numbers,horizontalsize):
    for j in range(i, i+horizontalsize):
        print (j, end=" ")
    print() #for the newline after every row

Your loop steps skips all the numbers between 1 and 1+horizontalsize, and you just print that number out (without worrying about putting things on the newline). You either need to insert a nested for loop, or modify your range to go over every number, and then put the newline only after specific ones.

That second solution, which uses modulo operator:

for i in range(1,(numbers+1)):
    print(i,end=" ")
    if i % horizontalsize == 0:
        print()

Which gives me:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15

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