总结并连接字符串的长度,使字符串的长度满足条件

Summing up and concatenating the length of strings such that length of the strings meets a condition

假设我有一个字符串列表,我想用它们制作一条推文。例如:

# should be two tweets total 
this_list = ["Today is monday tomorrow is tuesday the next" ,"will be friday and after that", "saturday followed by sunday", "this month is march the next", "april after that may followed", "by june then july then we", "have august then", "september and october finishing", "the year with november and december" ]

我想要的输出与此类似(当然存储在列表中):

tweet 1:  'Today is monday tomorrow is tuesday the next will be friday and after that saturday followed by sunday this month is march the next april'
tweet 2:  'after that may followed by june then july then we have august then september and october finishing the year with november and december'

我曾尝试使用 while 循环来实现此目的,但我不确定该循环是否正常工作...

out = [] # empty list
s = 0 # counter
tweet = "" # string to add too 
while s < 140:
    for x in this_list:
        tweet += x
        s += len(x)
    out.append(tweet)
print(len(out))


这不是最符合 Python 风格的方法。但它非常清楚并且以可见的方式分解了逻辑:

mylist = ['Today', 'is', 'monday', 'tomorrow', 'is', 'tuesday', 'the', 'next', 'will', 'be', 'friday', 'and', 'after', 'that', 'saturday', 'followed', 'by', 'sunday', 'this', 'month', 'is', 'march', 'the', 'next', 'april', 'after', 'that', 'may', 'followed', 'by', 'june', 'then', 'july', 'then', 'we', 'have', 'august', 'then', 'september', 'and', 'october', 'finishing', 'the', 'year', 'with', 'november', 'and', 'december']

position = 0 #We keep track of the position, because we might reach the end of the list without meeting the 140 chars criteria
n_chars = 0 #character counting variable
list_of_tweets = []
iter_string = ''
for word in mylist:

    if(n_chars < 140): #We keep adding words to our sentence as max number of chars is not reached
        iter_string = iter_string + word + ' '
        n_chars = n_chars + len(word) + 1 #+1 because of the space we add
        if(n_chars >= 140):
                    list_of_tweets.append(iter_string[:-1]) #We delete the last char as it is a space
                    iter_string = ''
                    n_chars = 0

    if(position == len(mylist)-1):
        list_of_tweets.append(iter_string[:-1])

    position = position + 1 #We are advancing to the next word in the iteration

print(list_of_tweets)

我最终使用了一个包含长度和文本的元组列表;然后对长度求和,直到遇到 140 个字符。

lot = [(len(i),i) for i in output] # list of tuples (length, txt)
out = [] # store tweets
y=0 # count len of tweets
t= '' # empty tweet 
for l, txt in lot:
    y += l
    t += txt
    if y >= 140:
        t= ''
        y = 0
    else:
        if y>= 119: # I want the 'full tweet' not building blocks
            print(t)
            out.append(t)

len(out) #number of tweets