简体   繁体   English

For循环替换列表元素

[英]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?我希望这段代码在大列表中的所有列表中用“*”替换每个“1”,但事实并非如此,有人可以解释原因并告诉我解决方案吗?

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: 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 * . area[list_num]是您的子列表,您将其替换为* 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:- 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, '*', '*', '*']]

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

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