Find the index of a certain value in a list in Python [duplicate]

1

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 this list of strings I used the code below but it does not work, I can not get the position of the word in my list of words to refer to in another list I will only store the amount of times it appears. Note: I need this to respect the position of the word with reference to the position. Ex: words [1] = 'house'     frequency [1] = 3

Frequency (Tweets list):

    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
    
asked by anonymous 11.06.2017 / 22:39

1 answer

2

I will not solve the question for you, but there are some tips:

Checking if an element is 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é')]

In this the result is a list of tuples with the word and the 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']
    
12.06.2017 / 00:06