嵌套列表数组删除附加

2024-09-30 04:34:35 发布

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

我正在学习一个叫做嵌套列表的Hackerrank问题,这里是链接https://www.hackerrank.com/challenges/nested-list/problem

我想问为什么我用了。删除,它不起作用。这是我使用的部分。删除:

# for i in range(len(scoreList)):  
#     if scoreList[i] == minScore:
#         scoreList.remove(scoreList[i]);
#         nameList.remove(nameList[i]);
# remove doesn't work. why?    

然而,当我使用.append时,它工作得很好。我不明白为什么。请你看一下,告诉我哪里出了问题,好吗?多谢各位

以下是我的解决方案,已被接受:

nestedList = [];

for _ in range(int(raw_input())):
    name = raw_input()
    score = float(raw_input())
    nestedList.append([name, score]);      
        
# print len(nestedList);
# print nestedList[1];
# print nestedList[1][0];

# for inner in nestedList:
#      for value in inner:
#          print value

nameList = [];
scoreList = [];

for i in range(len(nestedList)):
    currentName = nestedList[i][0];
    currentScore = nestedList[i][1];
    nameList.append(currentName);
    scoreList.append(currentScore);

minScore = min(scoreList);   

scoreNotMin = [];
nameNotMin = [];

for i in range(len(scoreList)):
    if scoreList[i] != minScore:
        scoreNotMin.append(scoreList[i]);
        nameNotMin.append(nameList[i]);

# for i in nameNotMin:
#     print i;
# ok check append works.


# for i in range(len(scoreList)):  
#     if scoreList[i] == minScore:
#         scoreList.remove(scoreList[i]);
#         nameList.remove(nameList[i]);
# remove doesn't work. why?        

            
secondMin = min(scoreNotMin);
# print secondMin

output = [];
for i in range(len(scoreNotMin)):
    if scoreNotMin[i] == secondMin: 
        output.append(nameNotMin[i]);
output.sort();
for i in output:
    print i;
    

多谢各位


Tags: inforoutputlenifrangeremoveprint
1条回答
网友
1楼 · 发布于 2024-09-30 04:34:35

我认为问题在于,在遍历列表时,列表的长度正在改变,因为您在这一行中使用了两次名称nameList

我猜你会遇到一个list index out of range错误

请尝试以下示例:

# this works
nameList = ['a', 'b']
nameList.remove(nameList[1])
>>> ['a']
# here you run into an error
nameList = ['a', 'b']
for i in range(len(nameList)):
    nameList.remove(nameList[i])

相关问题 更多 >

    热门问题