将string连接到列表中的下一个字符串

时间:2011-07-31 21:35:28

标签: python

我有一个包含大量单词的列表: sentence = ['a','list','with','a','lot','of','strings','in','it']

我希望能够通过列表并根据我的一些条件组合成对的单词。 e.g。

[ '一个', '列表', '与', 'A', '大量', '的', '弦', '在', '它'] 变 ['a list','with','a','of','strings','in','it']

我尝试过类似的事情:

for w in range(len(sentence)):
    if sentence[w] == 'a':
        sentence[w:w+2]=[' '.join(sentence[w:w+2])]

但它不起作用,因为加入字符串会减小列表的大小并导致索引超出范围。有没有办法用迭代器和.next()或其他东西呢?

6 个答案:

答案 0 :(得分:4)

您可以使用迭代器。

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

答案 1 :(得分:1)

这是就地工作的:

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)

产量

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

答案 2 :(得分:0)

您可以使用while周期并手动增加索引w

答案 3 :(得分:0)

一种天真的方法:

#!/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']

答案 4 :(得分:0)

这样的东西?

#!/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

输出:

a list
with
a lot
of
strings
in
it

答案 5 :(得分: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))