[英]Printing a multiplication table with nested loops?
I'm having a really hard time trying to figure out this exercise.我真的很难弄清楚这个练习。
Print the 2-dimensional list mult_table by row and column.按行和列打印二维列表mult_table。 Hint: Use nested loops.
提示:使用嵌套循环。 Sample output for the given program:
给定程序的示例输出:
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
This is the code that I have so far这是我到目前为止的代码
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
for row in mult_table:
for num in row:
print(num,' | ',end='|')
print()
What I get is this我得到的是这个
1 ||2 ||3 ||
2 ||4 ||6 ||
3 ||6 ||9 ||
I have no idea what I'm doing wrong!我不知道我做错了什么! I have also tried to do end=' ' but that still leaves a space and |
我也试过做 end=' ' 但这仍然留下一个空间和 | at the end of each row.
在每一行的末尾。 Please help.
请帮忙。 I am using Python 3 btw.
顺便说一句,我正在使用 Python 3。
You're overthinking this.你想多了。 One loop should be enough here.
在这里,一个循环就足够了。 You can unpack the inner lists and specify a
sep
parameter.您可以解压缩内部列表并指定
sep
参数。
for m in mult_table:
print(*m, sep=' | ')
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
If you want two loops, you will need to programmatically control the separators and the end characters to be printed out at each inner loop iteration.如果您想要两个循环,您将需要以编程方式控制分隔符和结束字符以在每次内部循环迭代时打印出来。
for i in mult_table:
for c, j in enumerate(i):
sep = '|' if c < len(i) - 1 else ''
end = ' ' if c < len(i) - 1 else '\n'
print(j, sep, end=end)
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
Use join with map:使用连接地图:
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
for row in mult_table:
print(" | ".join(map(str, row)))
Output:输出:
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9
Low-Level: Your code shows two '|'
低级:您的代码显示两个
'|'
after each number because that's what you're telling it to do (one of them is passed to print()
right after num
, and one of them is added by the use of end='|'
, which tells print()
to add a '|'
at the end of the printed string).在每个数字之后,因为这就是您要它执行的操作(其中一个在
num
之后立即传递给print()
,并且通过使用end='|'
添加其中一个,这告诉print()
添加打印字符串末尾的'|'
)。
Using end=''
avoids the second '|'
使用
end=''
避免了第二个'|'
, but you still end up with a pipe character at the end of each row from the print()
call. ,但您仍然会在
print()
调用的每一行末尾得到一个管道字符。
To get '|'
得到
'|'
between items, but not at the end of the row, you need to handle the last item in each row specially (or, better use " | ".join(row)
to add the separators automatically).在项目之间,但不是在行尾,您需要专门处理每行中的最后一个项目(或者,最好使用
" | ".join(row)
自动添加分隔符)。
High-Level: You're likely not solving this problem the way it was intended to be solved.高级:您可能没有按照预期的方式解决这个问题。
Your answer hard-codes the multiplication table, but you could be generating it as part of the loop, like:您的答案对乘法表进行了硬编码,但您可以将其作为循环的一部分生成,例如:
# Store the size of the table here
# So it's easy to change later
maximum = 3
# Make a row for each y value in [1, maximum]
for y in range(1, maximum + 1):
# Print all x * y except the last one, with a separator afterwards and no newline
for x in range(1, maximum):
print(x * y, end=' | ')
# Print the last product, without a separator, and with a newline
print(y * maximum)
This solves the specific problem given, but we can now change the value of "maximum" to also generate a square multiplication table of any size, and we don't have to worry about errors in our multiplication table.这解决了给定的特定问题,但我们现在可以更改“maximum”的值来生成任意大小的正方形乘法表,而且我们不必担心乘法表中的错误。
for row in mult_table:
line = 0
for num in row:
if line < len(mult_table) - 1:
print(num, '| ', end = '')
line += 1
else:
print(num)
This will iterate through each of the rows step by step checking through the if
statement to see if it has reached the end of the row, printing the |
这将逐步遍历每一行,检查
if
语句以查看它是否已到达行的末尾,并打印|
between each num
in the row
until the end which will simply print the num
followed by a return to next line. row
中的每个num
之间直到结束,这将简单地打印num
然后返回到下一行。
Placing the line = 0
inside the first loop is essential as putting it outside the first loop will cause line
to already meet the else
requirement of the if
statement.将
line = 0
放在第一个循环内是必不可少的,因为将它放在第一个循环之外将导致line
已经满足if
语句的else
要求。 With it inside the initial loop, each iteration causes line
to reset to 0
, which allows the nested if
to function properly.在初始循环中使用它,每次迭代都会导致
line
重置为0
,这允许嵌套的if
正常运行。
row_length = len(mult_table[0]) #Gets length of the first row.
for row_index, row in enumerate(mult_table): #Loops trough each row.
count = 1 #Sets count
cell_index = 0 #Sets cell index count
while count != row_length: #Checks if end of the row
print(f'{mult_table[row_index][cell_index]} | ', end='') #Print
count += 1 #Count increase
cell_index += 1 #Count increase
else:
print(f'{mult_table[row_index][cell_index]}') #Print
count += 1 #Count increase
cell_index += 1 #Count increase
Here is a solution using nested loops and without using .join.这是使用嵌套循环而不使用 .join 的解决方案。
This worked for me:这对我有用:
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
row_num = 0
for row in mult_table:
i = 0
for cell in row:
if i < len(mult_table) -1:
print(cell,'| ', end='')
i +=1
else: print(cell)
'''
Here is a solution I came up with.这是我想出的解决方案。 I haven't learned some of the things I see in the examples above, so I just made what I have learned work.
我在上面的例子中看到的一些东西我还没有学到,所以我只是把我学到的东西付诸实践。 My first post, I'm sure if it is ever seen I will learn etiquette and format etc... One problem I feel like exists, is the rowlen variable.
我的第一篇文章,我确定如果有人看到我会学习礼仪和格式等...我觉得存在的一个问题是 rowlen 变量。 I want it to be the amount of elements in the row, not the amount of nested list elements in the mult_table list.
我希望它是行中元素的数量,而不是 mult_table 列表中嵌套列表元素的数量。
# existing code
mult_table = [
[1, 2, 3],
[2, 4, 6],
[3, 6, 9]
]
# my code
# |
# \|/
# V
x = '| '
rowlen = len(mult_table) - 1
# print(x, rowlen) # testing values
for row in mult_table:
for cell in row[0:rowlen]:
print(cell, '{}'.format(x), end='')
print(row[rowlen])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.