开发者

joining string to next string in list

开发者 https://www.devze.com 2023-03-24 08:38 出处:网络
I have a list with a large number of words in it: sentence = [\'a\',\'list\',\'with\',\'a\',\'lot\',\'of\',\'strings\',\'in\',\'it\']

I have a list with a large number of words in it: sentence = ['a','list','with','a','lot','of','strings','in','it']

I want to be be able to go through the list and combine pairs of words according to some conditions I have. e.g.

['a','list','with','a','lot','of','strings','in','it'] becomes ['a list','with','a lot','of','strings','in','it']

I have tried something like:

for w in range(len(sentence)):
    if sentence[w] == 'a':
        sentence[w:w+2]=[' '.joi开发者_如何学Cn(sentence[w:w+2])]

but it doesn't work because joining the strings, decreases the size of the list and causes an index out of range. Is there a way to do this with iterators and .next() or something?


You can use an iterator.

>>> it = iter(['a','list','with','a','lot','of','strings','in','it'])
>>> [i if i != 'a' else i+' '+next(it) for i in it]
['a list', 'with', 'a lot', 'of', 'strings', 'in', 'it']


This works in-place:

sentence = ['a','list','with','a','lot','of','strings','in','it']

idx=0
seen=False
for word in sentence:
    if word=='a':
        seen=True
        continue
    sentence[idx]='a '+word if seen else word
    seen=False
    idx+=1    
sentence=sentence[:idx]
print(sentence)

yields

['a list', 'with', 'a lot', 'of', 'strings', 'in', 'it']


Somthing like this?

#!/usr/bin/env python

def joiner(s, token):
    i = 0
    while i < len(s):
        if s[i] == token:
            yield s[i] + ' ' + s[i+1]
            i=i+2
        else:
            yield s[i]
            i=i+1

sentence = ['a','list','with','a','lot','of','strings','in','it']

for i in joiner(sentence, 'a'):
    print i

outputs:

a list
with
a lot
of
strings
in
it


You can use while cycle and increase index w manually.


A naive approach:

#!/usr/bin/env python

words = ['a','list','with','a','lot','of','strings','in','it']

condensed, skip = [], False

for i, word in enumerate(words):
    if skip:
        skip = False
        continue
    if word == 'a':
        condensed.append(word + " " + words[i + 1])
        skip = True
    else:
        condensed.append(word)

print condensed
# => ['a list', 'with', 'a lot', 'of', 'strings', 'in', 'it']


def grouped(sentence):
    have_a = False
    for word in sentence:
        if have_a:
            yield 'a ' + word
            have_a = False
        elif word == 'a': have_a = True
        else: yield word

sentence = list(grouped(sentence))
0

精彩评论

暂无评论...
验证码 换一张
取 消