简体   繁体   中英

For loop replacing list elements

I expect this code to replace every "1" with a "*" in all of the lists inside the big list, but it's not doing so, can someone explain why and tell me a solution?

def display_map():
    area = [[1,1,1,2,1,1,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[2,0,0,0,0,0,2],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,1,1,2,1,1,1]]
    for list_num in range(len(area)):
        for walls in area[list_num]:
            if walls == 1:
                area[list_num] = '*'
    print(area)
display_map()

You can use a list comprehension like this instead:

def display_map():
    area = [[1,1,1,2,1,1,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[2,0,0,0,0,0,2],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,1,1,2,1,1,1]]
    area = [["*" if n == 1 else n for n in l] for l in area]
    print(area)

display_map()

Output:

[['*', '*', '*', 2, '*', '*', '*'], ['*', 0, 0, 0, 0, 0, '*'], ['*', 0, 0, 0, 0, 0, '*'], [2, 0, 0, 0, 0, 0, 2], ['*', 0, 0, 0, 0, 0, '*'], ['*', 0, 0, 0, 0, 0, '*'], ['*', '*', '*', 2, '*', '*', '*']]

area[list_num] is your sublist and you are replacing it with * . Change your code to this and try:-

def display_map():
    area = [[1,1,1,2,1,1,1],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[2,0,0,0,0,0,2],[1,0,0,0,0,0,1],[1,0,0,0,0,0,1],[1,1,1,2,1,1,1]]
    for list_num in range(len(area)):
        for w in range(len(area[list_num])):
            if area[list_num][w] == 1:
                area[list_num][w] = '*'
    print(area)

display_map()

Output:-

[['*', '*', '*', 2, '*', '*', '*'], ['*', 0, 0, 0, 0, 0, '*'], ['*', 0, 0, 0, 0, 0, '*'], [2, 0, 0, 0, 0, 0, 2], ['*', 0, 0, 0, 0, 0, '*'], ['*', 0, 0, 0, 0, 0, '*'], ['*', '*', '*', 2, '*', '*', '*']]

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