【问题标题】:use nested while loop to replace elements of list of lists使用嵌套的while循环替换列表列表的元素
【发布时间】: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


    【解决方案1】:

    这可以通过以下方式更简单地完成:

    def _execute():
        user_input = input("type in: ")
        return user_input
    
    def insertdata(lst, get_data):
      """ Inplace replacement of data in list 
          using function get_data """
      for row in range(len(lst)):
        for column in range(len(lst[row])):
          # Replacing items 1 by 1 
          # using function get_data
          lst[row][column] = get_data()
    
      return lst
    

    测试

    listoflist = [[None, None, None],[None, None, None]]
    
    # id(..) shows the in memory address of an object
    print(f'starting address listoflist {id(listoflist)}')
    # Test routine placing result in dummy_list
    dummy_list = insertdata(listoflist, _execute)
    print(f'ending address listoflist {id(listoflist)}')
    print(f'dummy list address {id(dummy_list)}')
    print(f'listof list: {listoflist}')
    print(f'dummy_list: {dummy_list}')
    

    输出

     starting address listoflist 139769341482560
    type in: 1
    type in: 2
    type in: 3
    type in: 4
    type in: 5
    type in: 6
    ending address listoflist 139769341482560
    dummy list address 139769341482560
    listof_list: [['1', '2', '3'], ['4', '5', '6']]
    dummy_list: [['1', '2', '3'], ['4', '5', '6']]
    

    我们看到 listoflist 具有相同的结束地址和起始地址 (139769341482560),因此我们只是对列表进行了变异,而不是创建一个新列表。

    dummy_list 与 listoflist 具有相同的地址,因此我们返回了相同的列表。

    【讨论】:

      【解决方案2】:

      为什么不只遍历数组并将数据放入其中?

      for i in range(len(listoflist)):
          for j in range(len(listoflist[i]):
              listoflist[i][j] = data
      

      【讨论】:

      • 我看到你编辑了你的问题。现在看起来您不希望数组中的所有值都相同,而是要一一输入。如果是这样,您可以使用 xbello 方法
      猜你喜欢
      • 2015-02-14
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2018-04-18
      • 2021-12-17
      • 2018-01-06
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多