如何修复程序,使其不重复或完全删除“信息”列表中的内容

时间:2019-01-27 15:51:49

标签: python pycharm

我正在编写一个程序,该程序应该从学生及其姓名中获得10个测试成绩,并将该信息放入列表中的列表中。我看到一个问题,我反复将内容追加到“信息”列表中,并获取重复数据。但是,当我尝试对其进行修复时,程序会不断返回空列表或仅包含第二组名称和测试分数的列表。我不知道为什么会这样,任何帮助都将不胜感激。

我尝试过:

  • del info [:]
  • info.clear()
  • 对于我在len(info)范围内:    info.pop()

w

testinfo = []
score = 0
testnum = 0
name = ''
info = []
info2 = []
name = input('Enter a student name')
while name != '0':
    info.append(name)
    for i in range(0, 10):
        testnum = testnum+1
        print('Enter a score for test', testnum)
        score = int(input())
        info.append(score)
    testnum = testnum-10
    testinfo.append(info)
    name = input('Enter a student name')
    del info[:]
print(testinfo)

预期结果:[[student1name,1testscore1,1testscore2,etc.],[student2name,2testscore1,2testscore2,etc.]]

实际结果:[[], []][[student2name,2testscore1,2testscore2,etc.], [student2name,2testscore1,2testscore2,etc.]]

2 个答案:

答案 0 :(得分:0)

尝试将信息直接附加到testinfo中以供使用:

testinfo.append(copy.deepcopy(info))

我认为您的问题是您的信息列表指向listinfo内的列表。因此,如果您删除信息列表,您还将删除信息列表的内容。 https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/。 我认为您需要导入副本。希望这可以帮助。

答案 1 :(得分:0)

info = []
  • 在内存中的某个地方创建一个新列表
  • 创建一个名为info的绑定,该绑定指向该内存区域
testinfo.append(info)
  • 创建绑定info的副本
  • 将该绑定存储在testinfo列表中
del info[:]
  • 删除与info关联的存储区域
  • testinfo中的绑定指向相同的存储位置,因此被删除

您可以简单地重新分配一个新的列表对象,而不必手动删除列表:

info = []

或将info放入循环范围。

相关问题