拆分,重新排列和连接for循环中的字符串

时间:2017-07-11 01:28:51

标签: python

我正在尝试根据逗号分隔列表的长度重新排列字符串。例如,以下字符串包含四个逗号,我们拆分用逗号分隔的字符串;我们得到四个清单。现在我们忽略那些长度(字数)小于或等于4的列表,并将它们合并到后续列表中,其字数或长度大于4。

使用以下代码,我按照它们的长度分隔了列表,但是无法弄清楚如何将它们连接起来以便获得看起来像的结果:

['In fact, a 2016 study published in the journal Current Biology shows that our bodies adjust to higher levels of activity', 'resulting in a decline in weight loss, even a reversal, after a few months']

代码:

import re


string = "In fact, a 2016 study published \
in the journal Current Biology shows that \
our bodies adjust to higher levels of activity, \
resulting in a decline in weight loss, \
even a reversal, after a few months"

pattern = re.compile("^\s+|\s*,\s*|\s+$")

small = []
big = []

for x in pattern.split(string):

    if 1 <= len(x.split()) <= 4:
        small.append(x)
    else:      
        big.append(x)

print small = ['In fact', 'even a reversal', 'after a few months']
print big = ['a 2016 study published in the journal Current Biology shows that our bodies adjust to higher levels of activity', 'resulting in a decline in weight loss']         

这是我自己问题的有效解决方案:

string = "In fact, a 2016 study published \
in the journal Current Biology shows that \
our bodies adjust to higher levels of activity, \
resulting in a decline in weight loss, \
even a reversal, after a few months"
listy= [x.strip() for x in string.split(',')] 
newstring= []

for segment in listy:

    if listy[len(listy)-1] != segment:

        if len(segment.split(' ')) > 4:
            newstring.append(segment+"&&")
        else:
            newstring.append(segment+",")

    else:

        newstring.append(segment)

newlisty= [x.strip() for x in (' '.join(newstring)).split('&&')]
print newlisty

感谢所有花时间回答我问题的人。

1 个答案:

答案 0 :(得分:0)

string = "In fact, a 2016 study published \
    in the journal Current Biology shows that \
    our bodies adjust to higher levels of activity, \
    resulting in a decline in weight loss, \
    even a reversal, after a few months"
listy=string.split(',') #split string by comma
newstring=[]
for segment in listy:
    if len(list(list(filter(None, segment.split(' ')))))>4: #sort out short strings
           newstring.append(segment) #add segment to the list
print(newstring)

结果是:

   [' a 2016 study published     in the journal Current Biology shows that     our bodies adjust to higher levels of activity', '     resulting in a decline in weight loss']