如何将for循环分成三组?蟒蛇

时间:2018-08-05 15:03:14

标签: python list for-loop

这是我的代码。

def twitter_get_tweets():
    try:
        twitter_stats_li = []
        for tweet, tweet_date, tweet_name, tweet_stats in zip(twitter_tweets, twitter_dates, twitter_tweet_name, twitter_stats):
            print tweet_name.get_text() + "\n"
            print tweet_date["title"] + "\n"
            print tweet.get_text() + "\n"
            x = tweet_stats.get_text() # Get tweet stats and append to list.
            twitter_stats_li.append(x)
            for index in range(len(twitter_stats_li)):
                    print twitter_stats_li[index]

    except NameError:
        print "Twitter account has no tweets! :("

这是我的输出。

13,364 replies .
7,852 retweets
31,664 likes
9,787 replies .
9,206 retweets
34,207 likes
20,314 replies .
7,532 retweets
29,890 likes
8,085 replies .
7,844 retweets
31,436 likes
5,160 replies .
7,375 retweets
32,101 likes
24,397 replies .
13,858 retweets
48,694 likes
10,173 replies
.8,879 retweets

这是我想发生的输出,但是我不知道如何编程。

13,364 replies 7,852 retweets 31,664 likes
9,787 replies 9,206 retweets 34,207 likes

那么我列表中的这三个元素合并为一个元素?

print twitter_stats_li

结果。

["13,364 replies 7,852 retweets 31,664 likes", "9,787 replies 9,206 retweets 34,207 likes"]

1 个答案:

答案 0 :(得分:0)

如果实际上tweet_stats总是为您返回3个变量,那么您的最后一行应该可以达到这种效果:

for idx in range(0, len(twitter_stats_li), 3):
   print(twitter_stats_li[idx:idx+3])