Callahan22
Posts: 5
Joined: Fri Oct 11, 2013 5:31 pm

Outputting contents of a list

Tue Oct 15, 2013 4:55 pm

So here's the problem. I want to populate a list with 20 numerical strings. Simple to do and done. I then want to list the contents of that list. In one sense I can but not the way I want to. So, this code works:

Code: Select all

printed_ids = []
for tweet in api.mentions_timeline(count = 20): #Get last 20 mentions
	if tweet.id not in printed_ids:
		printed_ids.append(tweet.id)
		print printed_ids
		print ""
and populates the printed_ids list with the last 20 IDs of tweets.
Good, exactly what I wanted. Now I want to print off the tweet text next to each of the various IDs so I add this code:

Code: Select all

for tweet in api.mentions_timeline(count = 20):
	if tweet.id not in printed_ids:
		printed_ids.append(tweet.id)
		print printed_ids
		print ""

for tweet.id in printed_ids:
	print "Tweet ID: %d %r" % (tweet.id, tweet.text)
	print ""
The result is that it lists all the 20 different IDs but repeats the tweet text from the first ID listing against every ID. As I understand it, if the first for loop steps through each of the IDs, why when I have a second one with the tweet.text in there does it not print out the text tied to each ID in succession?

Thanks for any pointers!

User avatar
paddyg
Posts: 2555
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Outputting contents of a list

Tue Oct 15, 2013 5:21 pm

you need to get the tweet.text from the api.etc I would probably use a dict something like

Code: Select all

printed_ids = []
tweet_texts = {}
for tweet in api.mentions_timeline(count = 20): #Get last 20 mentions
   if tweet.id not in printed_ids:
      printed_ids.append(tweet.id)
      tweet_text[tweet.id] = tweet.text
      print printed_ids
      print ""

for tweet.id in printed_ids:
   print "Tweet ID: %d %r" % (tweet.id, tweet_text[tweet.id])
   print ""
which is actually a slightly convoluted way of doing it but is a small increment on your original code, you don't really need *both* the list and dict!
or make printed_ids = [[twee.id, tweet.text],[tweet.id etc
PS also odd second bit. probably logical to do

Code: Select all

printed_ids.append([tweet.id, tweet.text])
####################  then later
for tweet in printed_ids:
   print "Tweet ID: %d %r" % (tweet[0], tweet[1])
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

Return to “Python”