[英]python nested loops with lists
ok So I am practiving a couple problems and have no idea how to start this one. 好的,所以我正在解决几个问题,并且不知道如何启动这个问题。 I do not understand really well how to do nested loops, so we are given a list that creates a smiley face, and then this instructions. 我不太清楚如何执行嵌套循环,因此我们给出了一个创建笑脸的列表,然后提供了此说明。
smiley = [[" ","#"," ","#"," "],
[" ","#"," ","#"," "],
[" ","#"," ","#"," "],
[" "," "," "," "," "],
["#"," "," "," ","#"],
[" ","#"," ","#"," "],
[" ","#","#","#"," "],
[" "," "," "," "," "]]
Create a new local variable based on smiley defined above. 根据上面定义的笑脸创建一个新的局部变量。 More strictly, your definition of this new variable needs to explicitly use the variable smiley. 更严格地说,您对此新变量的定义需要显式使用变量笑脸。 Use nested for loops to change the characters stored in your newly created local variable. 使用嵌套的for循环可更改存储在新创建的局部变量中的字符。 Do not add or remove any elements from any list. 不要从任何列表中添加或删除任何元素。 Only change/replace. 仅更改/替换。 You can, however, change and replace any of the characters with any other single characters. 但是,您可以使用任何其他单个字符更改和替换任何字符。 Return this local list of lists. 返回此本地列表列表。
so how do I do nested loops for these list and change their items without changing everything else?? 所以我该如何为这些列表嵌套循环并更改其项目而不更改其他所有项目?
I only have this but I don't think it is even how I should start, please help me 我只有这个,但我不认为这应该是我的起点,请帮助我
def moodSwing():
face = smiley.copy()
for each in face[:1]:
for each in face[1:2]:
Try the following to switch between "#"
and " "
at the desired row number and character number: 尝试以下操作在所需行号和字符号的"#"
和" "
之间切换:
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
Then do the following: 然后执行以下操作:
>>> frown = moodSwing(smiley, [(4, 0), (4, 4), (5, 1), (5, 2), (5, 3), (6, 1), (6, 2), (6, 3)])
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] = '#'
The above code flips characters. 上面的代码翻转字符。 item
is an element in the current list. item
是当前列表中的元素。
Use the indices to change elements. 使用索引来更改元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.