python嵌套循环列表

时间:2015-09-03 02:25:07

标签: python list nested-loops

好吧所以我正在练习一些问题并且不知道如何开始这个问题。我不太了解如何做嵌套循环,因此我们给出了一个创建笑脸的列表,然后是这个说明。

smiley = [[" ","#"," ","#"," "],
      [" ","#"," ","#"," "],
      [" ","#"," ","#"," "],
      [" "," "," "," "," "],
      ["#"," "," "," ","#"],
      [" ","#"," ","#"," "],
      [" ","#","#","#"," "],
      [" "," "," "," "," "]]

根据上面定义的笑脸创建一个新的局部变量。更严格来说,您对此新变量的定义需要明确使用变量smiley。 使用嵌套for循环更改存储在新创建的局部变量中的字符。不要添加或删除任何列表中的任何元素。只能更换/更换。但是,您可以使用任何其他单个字符更改和替换任何字符。 返回此本地列表列表。

那么如何为这些列表执行嵌套循环并更改其项目而不更改其他所有内容?

我只有这个,但我不认为我应该如何开始,请帮助我

def moodSwing():
face = smiley.copy()
for each in face[:1]:
    for each in face[1:2]:

2 个答案:

答案 0 :(得分:1)

请尝试以下操作,在所需的行号和字符编号之间切换"#"" "

def moodSwing(smiley, coords):
    face = list(smiley)
    for row, character in coords:
        for r in range(len(face)):
            for c in range(r):
                if r == row+1 and c == character+1:
                    if face[r][c] == " ":
                        face[r][c] = "#"
                    else:
                        face[r][c] = " "
    return face

然后执行以下操作:

>>> frown = moodSwing(smiley, [(4, 0), (4, 4), (5, 1), (5, 2), (5, 3), (6, 1), (6, 2), (6, 3)])

答案 1 :(得分:1)

for list_index, lst in enumerate(face):
    for item_index, item in enumerate(lst):
        if item == '#':
            face[list_index][item_index] = ' '
        else:
            face[list_index][item_index] = '#'  

以上代码翻转字符。 item是当前列表中的元素 使用索引来更改元素。