I am trying to create a list of words with 5 characters. I am using this approach
word = pd.read_csv('words.csv').values.tolist()
for x in word:
if len(x) != 5:
word.pop(x)word = pd.read_csv('words.csv').values.tolist()
for x in word:
if len(x) != 5:
word.pop(x)
But this set of codes returns this particular error
word.pop(x)
TypeError: 'list' object cannot be interpreted as an integer
Can someone help me understand the Type Error and Troubleshoot it
CodePudding user response:
pop
is a function to remove the ith element from a list. I guess from your code that x is not an integer. You can check this with type(x)
. I think you want the remove
function, which
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
source: https://docs.python.org/3/tutorial/datastructures.html
CodePudding user response:
There is a faster method to do this, depending on what your CSV looks like.
A CSV that looks like this:
WORD
test
david
hello
If you have a csv that looks like the above, you can filter out the non-5 letter words like so:
word = pd.read_csv('words.csv')
word = word[word["WORD"].apply(lambda x : len(x) == 5)]
will output:
david
hello
I would recommend checking out this StackOverflow answer: Filter string data based on its string length