简体   繁体   English

使用嵌套的for循环在python中打印简单矩阵

[英]Printing a simple matrix in python using nested for loops

I am having trouble with my assignment. 我在分配作业时遇到麻烦。

Print out a 3x3 matrix of “-”s using for loops. 使用for循环打印出3x3的“-”矩阵。

It should look like this: 它看起来应该像这样:

- - -
- - -
- - -

This is the closest I have come but it's not working 这是我最近来的,但是没有用

x = "-"
for i in range(3):
    for n in range(3):
        for x in range(3):
            print x,

You will need nested for loops to accomplish this. 您将需要嵌套的for循环来完成此操作。

I have been trying this for an hour with no luck, can someone please point me in the right direction? 我已经尝试了一个小时,但是没有运气,有人可以指出正确的方向吗?

for i in range(21/7):
   print ' '.join(['-' for _ in range(264/88)])

In your code, x is defined to be - , so you shouldn't enumerate over it. 在您的代码中, x定义为- ,因此您不应枚举它。 I edited your code to produce a working version. 我编辑了您的代码以生成一个有效的版本。

Note that in the internal loop you need to put spaces between the - , while in the external loop you want to move to the next line. 请注意,在内部循环中,需要在-之间放置空格,而在外部循环中,则需要移至下一行。

Here is the code for python 3: 这是python 3的代码:

x = "-" 
for i in range(3): 
    for n in range(3): 
        print(x, end=' ')
    print('\n')

Here is the code for python 2: 这是python 2的代码:

x = "-" 
for i in range(3): 
    for n in range(3): 
        print x,
    print('\n')

Very good start! 很好的开始!

Let's think through, what were you trying to achieve with your 3rd loop. 让我们仔细考虑一下,您想通过第三个循环实现什么。
(Hint: you don't need a third loop). (提示:您不需要第三个循环)。

If you talk out what you need to happen it becomes: 如果您说出需要做什么,它将变成:

1) print a "- " three times. 1)打印一次“-”三遍。 (inner loop) (内循环)
2) print a new line 2)打印新行
3) now go back and repeat steps 1) and 2) three times (outer loop) 3)现在返回并重复步骤1)和2)3次(外循环)

That would only be 2 loops, not 3. 那将是2个循环,而不是3个循环。

Try This: 尝试这个:

x = "- "
for i in range(3):
    for n in range(3):
        print x,
    print "\n"

You could even shorten this to 您甚至可以将其缩短为

for i in range(3):       # print the following line 3 times
    for n in range(3):   # print 3 dashes, separated by a space
        print "- ",
    print "\n"           # begin a new line

BTW, print x, is proper if using Python 2, but for Python 3, it will need to be changed to print(x, end='') . 顺便说一句,如果使用Python 2, print x,是合适的,但对于Python 3,则需要将其更改为print(x, end='')

construct a matrix using nested loop: 使用嵌套循环构造矩阵:

matrix = [[],[],[]]

for x in range(0,3):
  for y in range(0,3):
    matrix[x].append("-")

then print it: 然后打印:

for i in range(3):
  print(matrix[i])

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

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