2017-07-11 7 views
1

コンマ区切りリストの長さに基づいて文字列を再配置しようとしています。たとえば、次の文字列には4つのカンマが含まれ、カンマで区切られた文字列が分割されます。我々は4つのリストを得る。今度は、長さ(単語数)が4以下のリストを無視し、単語数または長さが4を超える後続のリストにそれらをマージします。次のコードでforループの文字列を分割、再配置、連結します。

は、私は彼らの長さごとにリストを分けているが、苦労はそれがどのように見える結果を得るように、戻ってそれらを連結する方法を考え出す:

['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 

ありがとうございました私の質問に答える時間をとったすべての人。

+0

'small'と' big'リストを連結するためにあなたのルールは何ですか? – stamaimer

+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'] 
+0

コードを実行しましたか? – stamaimer

+0

はい、私は自分のコードを実行しました –

+0

OPはリストを求めています。あなたの答えは文字列を返します。 – stamaimer

関連する問題