繁体   English   中英

我在 python 上写了一个简单的代码,但它没有按预期工作,有人可以帮助我吗

[英]I wrote a simple code on python, but it doesn't work as intended can someone help me

此代码将显示一个图像,其中 0 将成为“”,而 1 将成为“*”。 这将显示一个图像:

 picture = [ [0,0,0,1,0,0,0 ], [0,0,1,1,1,0,0 ], [0,1,1,1,1,1,0 ], [1,1,1,1,1,1,1 ], [0,0,0,1,0,0,0 ], [0,0,0,1,0,0,0 ] ]

要显示的图像应该是:

 * *** ***** ******* * *

我需要有人帮助我的代码:

 picture = [ [0,0,0,1,0,0,0 ], [0,0,1,1,1,0,0 ], [0,1,1,1,1,1,0 ], [1,1,1,1,1,1,1 ], [0,0,0,1,0,0,0 ], [0,0,0,1,0,0,0 ] ] row=0 col=0 picture[row][col] while row<=5: while col<=6: if picture[row][col]== False: picture[row][col]=" " col=1+col else: picture[row][col]="*" col=col+1 print(
    str(picture[row][0]) +" "+ str(picture[row][1]) +" "+ 
 str(picture[row][2])+" "+str(picture[row][3])+" "+str(picture[row][4])
    +" "+str(picture[row][5])+" "+str(picture[row][6])
          )
 row=row+1

我的代码产生了什么:

 0 0 1 0 0 0 0 1 0 0 0 1 0 0 0 * 0 0 0 * 0 0 * 0 *

提出几个小建议供参考。

  1. 当您确切知道要循环多少次时,可以使用 for 循环
  2. 使用is or not关键字判断bool类型数据和==

尝试这个:

picture = [
    [0, 0, 0, 1, 0, 0, 0],
    [0, 0, 1, 1, 1, 0, 0],
    [0, 1, 1, 1, 1, 1, 0],
    [1, 1, 1, 1, 1, 1, 1],
    [0, 0, 0, 1, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0]
]


for row in picture:
    for col in row:
        print(" " if not col else "*", end="")
    print()

不要害怕使用嵌套 for 循环。

for row in picture:
    
    line = ""
    for i in row:
        if i == 0:
            line += " "
        else:
            line += "*"
    print(line)

更简单的方法:

for row in picture:
    for col in row:
        print(end=' *'[col])
    print()

非常短的版本:

'\n'.join(''.join(map(' *'.__getitem__, row)) for row in picture)

暂无
暂无

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

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