我在Hackerrank上学习一个叫做嵌套列表的问题,这里是链接https://www.hackerrank.com/challenges/nested-list/problem。
我想问为什么当我使用。remove时,它不起作用。这是我使用。remove:
的部分# 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;
谢谢。
我认为问题是列表的长度在运行列表时发生了变化,因为您在这一行nameList.remove(nameList[i])
中使用了两次名称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])