2

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]=[' '.join(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?

Andrew Blevins
  • 167
  • 1
  • 9

6 Answers6

4

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']
JBernardo
  • 32,262
  • 10
  • 90
  • 115
  • This looks really elegant, but I don't quite understand what is going on. How would I add multiple conditions for joining? eg: if i != 'a' and next(it) != 'lot' – Andrew Blevins Jul 31 '11 at 22:02
  • the `next(it)` function will increment the iterator so the `for` loop will not use that value twice. – JBernardo Jul 31 '11 at 22:04
  • if you have multiple conditions, you may have to save `next(it)` to a variable and then check. You will not be able to use a comprehension but a simple for loop should work. – JBernardo Jul 31 '11 at 22:07
  • Oh my word. I just learnt something new about iterators and list comprehensions. Thank you. – craigs Jul 31 '11 at 22:19
1

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']
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

You can use while cycle and increase index w manually.

eugene_che
  • 1,997
  • 12
  • 12
0

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']
miku
  • 181,842
  • 47
  • 306
  • 310
0

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
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
0
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))
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153