Find the input of a certain value in a Python list

Asked

Viewed 6,789 times

1

Guys, I’m doing a function to count the words of a text without repeating them and with that, I also need to count how many times it appears inside that list of strings I used the code below but it doesn’t work, I can’t get the position of the word on my word list to reference another list that will only store the amount of times it appears. Note: I need this to respect the position of the word with reference to position. Ex: words[1] = 'home' frequency[1] = 3

def frequencia(listTweets):

    palavras = []
    freq_palavras = []
    for x in range(len(listaTweets)):
            tweet = listaTweets[x]
            listaP = separa_palavras(tweet)
            for p in listaP:
                    if p in palavras:
                            indice = palavras.index(p)
                            freq_palavras[indice] += 1
                    else:
                            palavras.append(p)              
    return palavras, freq_palavras
  • The current code returns me this error: freq_palavras[Indice] += 1 Indexerror: list index out of range

  • Hello Jhonatan! You can edit your question to include new information! :)

1 answer

3


I won’t settle the matter for you, but here are some tips:

Checking if an element is embedded in a list:

>>> 5 in [1,2,3,4,5]
True

Using index:

>>> [1,2,3,4,5].index(2)
3 

looking for a certain element:

>>> lst = ['josé', 'maria', 'joão', 'josé']
>>> [(n, lst[n]) for n, x in enumerate(lst) if x=='josé']
[(0, 'josé'), (3, 'josé')]

Here the result is a list of tuples with the word and position (index) in the original list.

Now one to 'extract' the elements without the repetitions:

>>> lst = ['josé', 'maria', 'joão', 'josé']
>>> s = set()
>>> unique = [x for x in lst if x not in s and not s.add(x)]    
>>> print(unique)
['josé', 'maria', 'joão']
  • Thanks, I got!

  • If you have succeeded with the answer, consider giving the acceptance. :-)

  • 1

    Sorry, I just started using stackoverflow, I don’t know much yet... I just accepted, sorry.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.