[英]Appending to a list of list in python
我正在嘗試使用 for 循環將 append 項目添加到列表列表中,但遇到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()
一旦 i = 1,Python 就會嘗試在列表中找到第二個值,但目前是[[0]]
。 所以沒有第二個列表可以讓你 append 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], ...]
,如果不是我弄錯了)。
# 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.