Py学习  »  Python

我在python上写了一个简单的代码,但它没有达到预期的效果。有人能帮我吗

J0J0 • 3 年前 • 1334 次点击  

此代码将显示一个图像,其中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
      *
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130946
文章 [ 3 ]  |  最新文章 3 年前
Makonede
Reply   •   1 楼
Makonede    3 年前

更简单的方法:

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

非常简短的版本:

'\n'.join(''.join(map(' *'.__getitem__, row)) for row in picture)
Fredericka
Reply   •   2 楼
Fredericka    3 年前

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

for row in picture:
    
    line = ""
    for i in row:
        if i == 0:
            line += " "
        else:
            line += "*"
    print(line)
maya
Reply   •   3 楼
maya    3 年前

提出了一些小建议供参考。

  1. 当您确切知道要循环多少次时,可以使用for循环
  2. 使用 关键字来确定布尔类型数据和==

试试这个:

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()