【问题标题】:Appending to a list of list in python附加到python中的列表列表
【发布时间】:2021-07-12 21:08:09
【问题描述】:

我正在尝试使用 for 循环将项目附加到列表列表中,但遇到 IndexError: list index out of range 错误。

class Solution:
    
    counter = [[]]
    
    def test(self):  
        i = 0
        while i < 5:
            Solution.counter[i].append(i)
            i += 1

        print(Solution.counter)

sol = Solution()
sol.test()

【问题讨论】:

  • 你没有 counter[1] 。它不应该是 counter[i] ,只是把 counter[0].append(i)
  • 这是一个列表列表,我想每次都将项目附加到不同的索引中。

标签: python list arraylist


【解决方案1】:

只要 i = 1,Python 就会尝试在列表中查找第二个值,但它当前为 [[0]]。所以没有第二个列表可以附加 1。但你可以这样做:

class Solution:

counter = [] # <--- Note this 

def test(self):  
    i = 0
    while i < 5:
        Solution.counter.append([i]) # <-- Appending list with i in it
        i += 1

    print(Solution.counter)

这应该有效(假设您希望 counter 成为 [[0], [1], [2], ...],否则我弄错了)。

【讨论】:

  • 我期待与您相同的预期输出,但我尝试了这个,仍然得到相同的错误。
  • 抱歉,这行得通,但有什么办法可以选择我附加的索引。
  • 为此,你可以看看insert()programiz.com/python-programming/methods/list/insert你可以用它来代替append()
  • 您好,很抱歉有这么多问题,但我正在尝试将一个项目附加到具有给定索引的数组数组中。例如,如果存在列表 [[1],[2,4,6],[100,101,102]] 并且我想将 8 附加到第一个索引,那么它将变为 [[1],[2,4,6,8],[100,101,102]]
【解决方案2】:
# I have checked it, its running

class Solution:
    
    counter = []
    
    def test(self):  
        i = 0
        while i < 5:
            Solution.counter.append(i)
            i += 1

        print(Solution.counter)

sol = Solution()
sol.test()

【讨论】:

  • 欢迎来到 Stack Overflow! Stack Overflow 旨在促进学习。出于这个原因,答案不仅应该包括更正或改进的代码,还应该包括对如何为什么实现工作的解释。没有任何解释的代码转储很少有帮助,即使代码“应该是自我解释的”,添加解释也能确保每个人都能理解。请编辑您的答案并解释它如何回答所提出的具体问题。见How to Answer
猜你喜欢
  • 2021-11-13
  • 1970-01-01
  • 2017-12-18
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2019-03-29
相关资源
最近更新 更多