How to limit loop when using cursor in python

240
March 05, 2018, at 03:32 AM

I'm iterating over tweets using :

for status in tweepy.Cursor(api.user_timeline, screen_name='@realDonaldTrump').items():

But I want just the first 1000 items.

I can define an variable i=0 outside of the loop and then use if and i=i+1 to check if I've iterated enough. But it doesn't feel "pythony...", more C style

I've hoped there is some trick to it, like:

for status, i in (tweepy.Cursor(api.user_timeline, screen_name='@realDonaldTrump').items(), np.arange(10)):

Which of course doesn't work

Thanks

Answer 1

Use islice to do something similar to list[:10]:

from itertools import islice
cursor = tweepy.Cursor(api.user_timeline, screen_name='@realDonaldTrump').items()
for status in islice(cursor, 10):
    pass

To keep track of the index you can use the built-in enumerate:

for i, status in enumerate(cursor):
    pass
Rent Charter Buses Company
READ ALSO
TypeError: unsupported operand type(s) for -: 'method' and 'method' (Python)

TypeError: unsupported operand type(s) for -: 'method' and 'method' (Python)

I am working with datasets and dataframes (Python) and I want to express the ratio of the median of a certain set of values, by means of taking the absolute value of (mean-median)/median

257
How to create folded edges with css

How to create folded edges with css

Image i need to create with css

165
Grayscale filter on text, removes part of the text on Ghost's Casper

Grayscale filter on text, removes part of the text on Ghost's Casper

I've been searching the web for quite a while and couldn't find an answer

142
How can I add the new “Button” at the edge of side nav

How can I add the new “Button” at the edge of side nav

what is the best way to put the button at the edge of sidenav?

171