Python附加到列表列表

2024-04-20 15:26:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图简单地附加到列表列表中,但找不到一个清晰的示例来说明如何执行该操作。我看了几十个例子,但它们都是用于附加到一维列表或扩展列表的

示例代码:

testList = []
print(testList)
testList.append(3000)
print(testList)
testList[3000].append(1)
testList[3000].append(2)
print(testList)

预期结果:

testList[3000][1, 2]

实际结果:

[]
[3000]
Traceback (most recent call last):
  File ".\test.py", line 5, in <module>
    testList[3000].append(1)
IndexError: list index out of range

Tags: 代码pytest示例most列表call例子
3条回答

首先,感谢大家的快速回复。你们中的一些人让我朝着正确的方向思考,但我最初的问题并不完整(抱歉),所以我在这里添加了更多的上下文,希望对将来的其他人有所帮助

wp-overwatch.com唤起了我的记忆,我意识到在我的应用程序中只使用字典几天后,我把“3000”当作字典键,而不是列表索引。(“3000”是一个ID号的示例,我必须使用它来跟踪其中一个号码列表。)

然而,我不能使用字典,因为我需要添加新条目,删除第一个条目,并计算我正在处理的数字的平均值。答案是创建一个列表字典

我使用的示例测试代码:

testDict = {}
blah10 = 10
blah20 = 20
blah30 = 30
blah40 = 40

exampleId = 3000

if exampleId == 3000:
    testDict[3000] = []
    testDict[3000].append(blah10)
    testDict[3000].append(blah20)
    print(testDict)
    testDict[3000].pop(0) # Remove first entry
    print(testDict)
    testDict[3000].append(blah30) # Add new number to the list
    average = sum(testDict[3000]) / len(testDict[3000])
    print(average)
if exampleId == 3001:
    testDict[3001].append(blah30)
    testDict[3001].append(blah40)

结果:

{3000: [10, 20]}
{3000: [20]}
25.0

这是因为根据您的程序,python解释器将在列表中查找3000索引,并尝试将给定的数字附加到3000索引中,但没有该数字,因此它将打印错误

要解决此问题,请执行以下操作:

testList = []
print(testList)
testList.append(3000)
print(testList)
testList.append([1])
testList[1].append(2)
print(testList)

使用索引可以像我附加的那样附加值

testList[3000].append(1)正在告诉Python获取列表中的第3000项,并对其调用append函数。由于列表中没有3000项,因此会出现该错误

如果您希望通过值(如3000)而不是通过其在列表中的位置来查找项目,那么您需要的不是列表而是dictionary

使用字典,您可以执行以下操作:

>>> testList = {} # use curly brackets for a dictionary
>>> print(testList)
{}
>>> testList[3000] = [] # create a new item with the lookup key of 3000 and set the corresponding value to an empty list
>>> print(testList)
{3000: []}
>>> testList[3000].append(1)
>>> testList[3000].append(2)
>>> print(testList)
{3000: [1, 2]}
>>>

相关问题 更多 >