Home > database >  What am I doing wrong in this Python function?
What am I doing wrong in this Python function?

Time:12-16

I keep trying to create a loop that deletes everything in a given list that is not an integer.

If I attempt to use an if statement, it will get to the first integer it finds, and ignore my else: continue.

If I attempt to use a while loop, it will claim that the word is not in the list, even though the program literally pulls the word from the list directly.

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())

CodePudding user response:

Thank you to S3DEV for the idea to add, not subtract, and to both S3DEV and DarrylG for bringing up the fact that the split is actually a list of strings, which is glaringly obvious now.

Here is how I used this information to solve my issue (I also temporarily removed my functions to help with clarity):

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)

This provides me with only the numbers from the list and is exactly what I needed!

Thank you to all that answered!

  • Related