Python 在For While循环之后不再定义列表
我正在编写一个脚本,我想去掉一个嵌套列表,该列表是从文本文件中排序数据时创建的。删除嵌套列表并将其放入“已清理”列表后,我想对该列表进行排序并删除不需要的信息。我的问题出现在打印列表时。在for循环之前键入print时,它会正确打印。之后,我得到一个错误,当列表在顶部明确定义并在程序的前面引用时,列表没有定义 这是在for循环之后打印时出现的错误:Python 在For While循环之后不再定义列表,python,python-3.x,Python,Python 3.x,我正在编写一个脚本,我想去掉一个嵌套列表,该列表是从文本文件中排序数据时创建的。删除嵌套列表并将其放入“已清理”列表后,我想对该列表进行排序并删除不需要的信息。我的问题出现在打印列表时。在for循环之前键入print时,它会正确打印。之后,我得到一个错误,当列表在顶部明确定义并在程序的前面引用时,列表没有定义 这是在for循环之后打印时出现的错误: Traceback (most recent call last): File "DIRECTORY OF PROGRAM.py&qu
Traceback (most recent call last):
File "DIRECTORY OF PROGRAM.py", line 64, in <module>
print(clnwrd)
NameError: name 'clnwrd' is not defined
在有人问我之前,我检查了身份,确保打印语句在for循环之外。欢迎提供任何帮助。错误出现在代码的一行中:
del clnwrd
我想你的意思可能是:
def clnwrd[index of value]
以下代码适用于我:
完整代码:
import os
import sys
words = []
clnwrd = []
# checks for apostrophes
def apostro(value):
if value == '\'':
return True
else:
return False
# removes nesting lists
def nonest(x, newlist):
for y in x:
for z in y:
newlist.append(str(z))
return newlist
# opens file
with open('Path to specified file', 'r') as data:
for line in data:
word = ""
for character in line:
# skips apostrophes
if character == '\'':
pass
else:
# adds words to the list
word += str(character)
# splits words by selected character
if "THINg" in word:
words.append(word.split("THING"))
if "THING" in word:
words.append(word.split("THING"))
else:
words.append(word.split("Key."))
nonest(words, clnwrd)
print(clnwrd) # THE PRINT STATEMENT WORKS HERE
idx = 0
for thing in clnwrd:
if "THING" in thing:
del clnwrd[idx]
if "THING" in thing:
thing.split("THING")
if "THING" in thing:
thing.split("THING")
idx += 1
print(clnwrd) # PRINT STATEMENT WORKS HERE AS WELL
说明:
import os
import sys
words = []
clnwrd = []
# checks for apostrophes
def apostro(value):
if value == '\'':
return True
else:
return False
# removes nesting lists
def nonest(x, newlist):
for y in x:
for z in y:
newlist.append(str(z))
return newlist
# opens file
with open('Path to specified file', 'r') as data:
for line in data:
word = ""
for character in line:
# skips apostrophes
if character == '\'':
pass
else:
# adds words to the list
word += str(character)
# splits words by selected character
if "THINg" in word:
words.append(word.split("THING"))
if "THING" in word:
words.append(word.split("THING"))
else:
words.append(word.split("Key."))
nonest(words, clnwrd)
print(clnwrd) # THE PRINT STATEMENT WORKS HERE
idx = 0
for thing in clnwrd:
if "THING" in thing:
del clnwrd[idx]
if "THING" in thing:
thing.split("THING")
if "THING" in thing:
thing.split("THING")
idx += 1
print(clnwrd) # PRINT STATEMENT WORKS HERE AS WELL
如果未指定索引,del
用于删除整个列表:
要了解Python中del
的更多信息,请访问:
如果
“THING”
在THING
中,那么你del clnwrd
-它在那之后几乎消失了,所以我假设“THING”
在THING
中?你删除它,然后问我们为什么找不到它?我还看到str.split
调用本身没有保存结果。我想你应该再看看你正在使用的任何教学材料。用你自己的话来说,你认为del clnwrd是什么意思?哇,我觉得自己像个白痴。我盯着它看了几个小时,认为它删除了指定的索引,而不是整个列表。非常感谢。