在For While循环之后不再定义列表



我正在编写一个脚本,我想去掉在从文本文件中排序数据时创建的嵌套列表。在移除嵌套列表并将其放置在";"清洁";列表中,我想对该列表进行排序,并删除不需要的信息。我在打印列表时出现了问题。在for循环之前键入print时,它会正确打印。之后,我得到了一个错误,指出当列表在顶部明确定义并在程序的早期引用时,它没有被定义。

这是我在for循环之后打印时得到的错误:

Traceback (most recent call last):
File "DIRECTORY OF PROGRAM.py", line 64, in <module>
print(clnwrd)
NameError: name 'clnwrd' is not defined

这是我的代码:

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
for thing in clnwrd:
if "THING" in thing:
del clnwrd

if "THING" in thing:
thing.split("THING")
if "THING" in thing:
thing.split("THING")

# IF print(clnwrd) IS PLACED RIGHT HERE it DOESN'T WORK

在有人问之前,是的,我检查了身份,并确保打印声明在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

解释:

如果未指定索引,则使用del删除整个列表:要了解有关Python中del的更多信息,请访问:

https://www.w3schools.com/python/ref_keyword_del.asp

最新更新