简体   繁体   中英

Changing the values in multiple parts of a grid (list of strings?)

I'm making a 10-by-10 grid of 0 s. I want to be able to change (for example) the top 5 rows to "ONE" through an if statement.

What's the best way to go about doing it without targeting each individual 0 ?

I've tried doing something like grid[:5][:5] to target multiple 0 s, but that doesn't do anything.

grid = [[0 for x in range(10)] for y in range(10)]

number = 1

if number is 1:
    grid[:5][:5] = "ONE"

for row in grid:
    print(" ".join(map(str, row)))

You can use two nested for loops:

for row in range(5):
    for col in range(10):
        grid[row][col] = 'ONE'

As grid[:5][:5] returns a new list, changing the new list would not yield the results you want.

grid = [[0]*10 for x in range(10)] #pythonic way of making a list/list of list (grid)

number = 1
if number == 1:
    for x in xrange(5):
        for y in xrange(10):
            grid[x][y] = "ONE"

print(grid)

Output:

[['ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE'],
 ['ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE'],
 ['ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE'],
 ['ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE'],
 ['ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE', 'ONE'],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

You can do it, too, within list comprehension :

grid = [[0 for x in range(10)] for y in range(10)]

number = 1
if number == 1:
    grid = [["ONE" if y <5 else 0 for x in range(10)] for y in range(10)]

for k in grid:
    print(" ".join(map(str,k)))

Output:

ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE
ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE
ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE
ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE
ONE ONE ONE ONE ONE ONE ONE ONE ONE ONE
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

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