[英]What am I doing wrong in this Python function?
我一直在嘗試創建一個循環來刪除給定列表中不是 integer 的所有內容。
如果我嘗試使用 if 語句,它將到達它找到的第一個 integer,並忽略我的 else:繼續。
如果我嘗試使用 while 循環,它會聲稱該詞不在列表中,即使程序直接從列表中提取該詞也是如此。
error_lst = []
file_name = input("Enter in the name of the file. \n")
error_file = open(file_name, "r")
#Creates Python list from individual words in files.
def txt_to_lst():
for eachWord in error_file:
error_lst.extend(eachWord.split())
return error_lst
txt_to_lst()
for eachword in txt_to_lst():
while type(eachword) != int:
keyworddeleter = txt_to_lst().index(eachword)
txt_to_lst().pop(keyworddeleter)
# elif type(eachword) == int:
# continue
#return txt_to_lst()
print(txt_to_lst())
#print(word_scrubber())
感謝 S3DEV 提出加法而不是減法的想法,感謝 S3DEV 和 DarrylG 提出拆分實際上是字符串列表的事實,這現在非常明顯。
以下是我如何使用這些信息來解決我的問題(我還暫時刪除了我的功能以幫助清楚):
error_lst = []
file_name = input("Enter in the name of the file. \n")
error_file = open(file_name, "r")
#Creates Python list from individual words in files.
for eachWord in error_file:
error_lst.extend(eachWord.split())
int_lst = []
for i in range(0, len(error_lst)):
try:
error_lst[i] = int(error_lst[i])
except:
continue
for eachword in error_lst:
if type(eachword) == int:
int_lst.append(eachword)
print(int_lst)
這只為我提供了列表中的數字,這正是我所需要的!
謝謝大家的回答!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.