【发布时间】:2014-04-18 05:05:50
【问题描述】:
我正在尝试纠正一个程序,该程序接受一个嵌套列表,并返回一个取出专有名词的新列表。
这是一个例子:
L = [['The', 'name', 'is', 'James'], ['Where', 'is', 'the', 'treasure'], ['Bond', 'cackled', 'insanely']]
我想回来:
['the', 'name', 'is', 'is', 'the', 'tresure', 'cackled', 'insanely']
请注意,“where”已被删除。没关系,因为它没有出现在嵌套列表中的其他任何地方。每个嵌套列表都是一个句子。我的方法是将嵌套列表中的每个第一个元素附加到 newList。然后我比较看看 newList 中的元素是否在嵌套列表中。我会将 newList 中的元素小写以进行检查。我已经完成了这个程序的一半,但是当我尝试从最后的 newList 中删除元素时遇到了错误。一旦我得到新的更新列表,我想从 newList 中的nestedList 中删除项目。我最后将嵌套列表中的所有项目附加到 newerList 并将它们小写。应该这样做。
如果有人有更有效的方法,我很乐意倾听。
def lowerCaseFirst(L):
newList = []
for nestedList in L:
newList.append(nestedList[0])
print newList
for firstWord in newList:
sum = 0
firstWord = firstWord.lower()
for nestedList in L:
for word in nestedList[1:]:
if firstWord == word:
print "yes"
sum = sum + 1
print newList
if sum >= 1:
firstWord = firstWord.upper()
newList.remove(firstWord)
return newList
请注意,由于倒数第二行的错误,此代码未完成
这里是更新列表(updatedNewList):
def lowerCaseFirst(L):
newList = []
for nestedList in L:
newList.append(nestedList[0])
print newList
updatedNewList = newList
for firstWord in newList:
sum = 0
firstWord = firstWord.lower()
for nestedList in L:
for word in nestedList[1:]:
if firstWord == word:
print "yes"
sum = sum + 1
print newList
if sum >= 1:
firstWord = firstWord.upper()
updatedNewList.remove(firstWord)
return updatedNewList
错误信息:
Traceback (most recent call last):
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 80, in lowerCaseFirst
ValueError: list.remove(x): x not in list
【问题讨论】:
-
你没有提到错误实际上是什么,但你不能在迭代列表时更改它。为什么不将您想要的项目添加到新列表中,而不是尝试从旧列表中删除您不想要的项目?如果您需要更一般的反馈,请尝试codereview.stackexchange.com
-
第一个“The”是小写的吗?
标签: python