我要求输入(X)并打印 1 - 1000。X 用于每行打印 X 个整数。我如何实现这一目标?
perLine = int(input("How many numbers per line would you like: "))
for lineVariable in range(1, 1000, 1):
print(lineVariable)
示例输出(5)
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
最佳答案
以下内容满足您的要求:
per_line = int(input("How many numbers per line would you like: "))
for number in range(1, 1001):
print(number, end = " " if number % per_line else "\n")
为您提供以下输出:
How many numbers per line would you like: 10
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
.
.
981 982 983 984 985 986 987 988 989 990
991 992 993 994 995 996 997 998 999 1000
或者使用 Python 的 grouper recipe 的版本
per_line = int(input("How many numbers per line would you like: "))
for line in zip(*[iter(range(1, 1001))] * per_line):
print(" ".join([str(x) for x in line]))
关于Python 3.4.3 - 每行打印多个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573271/