简体   繁体   English

python打印列表项在线增加

[英]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. 我正在尝试接受用户输入,并以框格式将数字列表打印到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: 用户将输入高度和宽度,如果高度输入为5而宽度输入为3,则应打印:

1 2 3 1 2 3

4 5 6 4 5 6

7 8 9 7 8 9

10 11 12 10 11 12

13 14 15 13 14 15

right now im currently getting: 目前我正在得到:

1 1

4 4

7 7

10 10

13 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: 您还可以通过列表理解来声明2D列表,例如:

>>> 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. 您正在使用的range()将从1开始,增加到numbers ,然后每次增加一次horizontalsize You are pulling your values for i directly from that range, so those will be the only values you get. 您将直接从该范围提取i的值,因此这些将是您获得的唯一值。 One simple solution is to add a second, nested loop to generate the missing values (between i and i+horizontalsize ). 一种简单的解决方案是添加第二个嵌套循环以生成缺失值(在ii+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). 您的循环步骤将跳过1到1 +水平尺寸之间的所有数字,而您只需打印出该数字即可(不必担心将内容放在换行符上)。 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. 您要么需要插入一个嵌套的for循环,要么修改范围以遍历每个数字,然后仅将换行符放在特定的数字之后。

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 1 2 3
4 5 6 4 5 6
7 8 9 7 8 9
10 11 12 10 11 12
13 14 15 13 14 15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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