我正在学习使用python而且我已经坚持使用这段代码。
我想要显示行,但我要获取列。 我尝试了不同的变化,我得到一个while循环但是 我仍然得到for循环列。
Start_num = 0
Max_num = 200
while Start_num < 201:
for Number in range (Max_num, -1, -25):
print(Start_num, end=' ')
Start_num += 25
print(Number)
这是输出当前查找此代码的方式。
0 200
25 175
50 150
75 125
100 100
125 75
150 50
175 25
200 0
必须有办法获得两行而不是列,请帮忙。
答案 0 :(得分:5)
试试这个:
Start_num = 0
Max_num = 200
row1 = []
row2 = []
while Start_num < 201:
for Number in range (Max_num, -1, -25):
row1.append(str(Start_num))
Start_num += 25
row2.append(str(Number))
print(" ".join(row1))
print(" ".join(row2))
您需要提前构建行,然后在最后打印它们。终端仅以文本形式输出,没有行或列的概念。
答案 1 :(得分:2)
作为一般规则,您可以使用惯用语zip(*rows)
交换行和列。你的代码并不是那么构建的,但改变它是微不足道的。
# Your code, re-factored
results = zip(range(0, 201, 25), range(200, -1, -25))
# gives you a zip object that looks something like:
# # [ (0, 200), (25, 175), (50, 150), ..., (200, 0) ]
#
# you could duplicate your output with:
# # for pair in results:
# # print(*pair)
#
# N.B. this would exhaust the zip object so you couldn't
# use it below without re-calculating results = zip(range(...
swapped_results = zip(*results)
# gives you a zip object that looks something like:
# # [ (0, 25, 50, ..., 200), (200, 175, 150, ..., 0) ]
for row in swapped_results:
print(*row)
# 0 25 50 75 100 125 150 175 200
# 200 175 150 125 100 75 50 25 0