【发布时间】:2020-09-11 21:41:16
【问题描述】:
我想用这个函数的输出改变现有嵌套列表的元素
listoflist = [[None, None, None],[None, None, None]]
def _execute():
user_input = input("type in: ")
return user_input
输出应该是:
output execute() = 1
[[1, None, None],[None, None, None]]
output execute() = 4
[[1, 4, None],[None, None, None]]
任务不是使用新列表
insertdata 的预期行为应该是
数据从def _execute(): 传递到insertdata
列表的现有值被一个一个替换,直到每个值都被替换
我的方法是嵌套的 while 循环,其中包含嵌套列表的行和列的两个计数器: 主 while 循环启动第二个 while 循环 在第二个 while 循环中,第一行的值被替换 如果是这样,操作应该进行到下一行
def insertdata(data):
row_index = 0
while row_index != len(listoflist):
# inner loop
data_added = False
n = len(listoflist[row_index])
index = 0
while not data_added and index != n:
if listoflist[row_index][index] is None:
listoflist[row_index][index] = data
data_added = True
else:
index += 1
# gets not executed
if index == n:
row_index += 1
break
正确的行为是第一个传入的值替换列表的所有现有值
所以看起来第二个循环没有重新启动以逐个替换每个值
我在这里错过了什么?
完整示例:
"""
tasks
"""
listoflist = [[None, None, None],[None, None, None]]
def _execute():
user_input = input("type in: ")
return user_input
def insertdata(data):
row_index = 0
while row_index != len(listoflist):
# inner loop
data_added = False
n = len(listoflist[row_index])
index = 0
while not data_added and index != n:
if listoflist[row_index][index] is None:
listoflist[row_index][index] = data
data_added = True
else:
index += 1
# gets not executed
if index == n:
row_index += 1
break
while True:
insertdata(_execute())
print(listoflist)
【问题讨论】:
标签: python list while-loop nested-loops