简体   繁体   中英

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

This code will display an image where the 0 is going to be ' ', and the 1 is going to be '*'. This will reveal an image:

 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 ] ]

The image to be revealed should be:

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

The code that I need someone to help me with:

 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

What my code produces:

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

A few small proposals are suggested for reference.

  1. you can use for loops when you know exactly how many times you want to loop
  2. Use the is or not keyword to determine bool type data and ==

try this:

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

Don't be scare to use nested for loops.

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

Simpler method:

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

Very short version:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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