简体   繁体   中英

Python list not appending correctly in a loop

I'm doing a Tweepy/Django/nltk project where I have a list that will update for the searched tweets. Here's the part where I'm having a problem:

query = 'happy'
max_tweets=5
search_results = {}
sentiments = {}
sentilist = []
for status in tweepy.Cursor(api.search,  q=query).items(max_tweets):
    search_results[status.text] = unicode(status.text)
    search_results[status.text] = search_results[status.text].replace('|', ' ')
    search_results[status.text] = search_results[status.text].replace('\n', ' ')
    print(senti.linearsvc10(status.text))
    sentiments['tweet'] = unicode(search_results[status.text])
    sentiments['sentiment'] = senti.linearsvc10(unicode(status.text))
    sentilist.append(sentiments)
    print('inloop sentiments')
    print sentiments
    print('inloop sentilist')
    print sentilist

print('sentiments')
print sentiments
print('sentilist')    
print sentilist

basically, sentiments will equal to

{'tweet': 'Actual tweet here', 'sentiment': 'pos'}

So for each run of the loop, I want the sentiments to append to the list, so by the end of that, I will have 5 different objects in the list. But what actually happens is for each append to sentilist, it changes each item in the list to the last object that was appended. Example, the following would be individual sentiments objects:

{'tweet': 'tweet1', 'sentiment': 'pos'}
{'tweet': 'tweet2', 'sentiment': 'neg'}
{'tweet': 'tweet3', 'sentiment': 'neg'}
{'tweet': 'tweet4', 'sentiment': 'pos'}
{'tweet': 'tweet5', 'sentiment': 'neg'}

when appending to sentilist should be:

[{'tweet': 'tweet1', 'sentiment': 'pos'},
{'tweet': 'tweet2', 'sentiment': 'neg'},
{'tweet': 'tweet3', 'sentiment': 'neg'},
{'tweet': 'tweet4', 'sentiment': 'pos'},
{'tweet': 'tweet5', 'sentiment': 'neg'}]

but instead it becomes:

[{'tweet': 'tweet5', 'sentiment': 'neg'},
{'tweet': 'tweet5', 'sentiment': 'neg'},
{'tweet': 'tweet5', 'sentiment': 'neg'},
{'tweet': 'tweet5', 'sentiment': 'neg'},
{'tweet': 'tweet5', 'sentiment': 'neg'}]

Other parts of my codes work and I feel like there's a simple solution for this but I still can't figure it out.

You need to make a new dictionary sentiments in each loop:

for status in tweepy.Cursor(api.search,  q=query).items(max_tweets):
    sentiments = {}

You override the values in the same dictionary again and again and append this same dictionary in each loop. Therefore, you see the values for your last dictionary update in all entries in the list sentilist .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM