Adding strings in lists together

Mat*_*tjo 12 python string list

I want to transform the list ["A","B","A","A","B"] to the list ["AB","BA","AA","AB"].

I have tried to define a new list in which the first element is deleted and then add the strings of the lists together. After which I plan to delete the last element of the new list to get the result.

lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]
Run Code Online (Sandbox Code Playgroud)

But all I get is

TypeError: 'list' object cannot be interpreted as an integer

Any help is welcome.

Edit : Thank you guys, all your solutions worked perfectly :)

U10*_*ard 13

Best solution, using zip, cleverest:

>>> l = ["A","B","A","A","B"]
>>> [x + y for x, y in zip(l, l[1:])]
['AB', 'BA', 'AA', 'AB']
>>> 
Run Code Online (Sandbox Code Playgroud)

Or use this list comprehension:

>>> l = ["A","B","A","A","B"]
>>> [v + l[i + 1] for i, v in enumerate(l[:-1])]
['AB', 'BA', 'AA', 'AB']
>>> 
Run Code Online (Sandbox Code Playgroud)


Roa*_*ner 12

Use zip():

>>> lst = ["A","B","A","A","B"]
>>> [x + y for x, y in zip(lst, lst[1:])]
['AB', 'BA', 'AA', 'AB']
Run Code Online (Sandbox Code Playgroud)


Olv*_*ght 6

您可以使用map()

s = list(map(str.__add__, lst[:-1], lst[1:]))
Run Code Online (Sandbox Code Playgroud)

更好用operator.concat()(感谢建议,@ MykolaZotko):

import operator

s = list(map(operator.concat, lst[:-1], lst[1:]))
Run Code Online (Sandbox Code Playgroud)

更新。

我决定对更大的数据进行一些测试。

import operator

lst = [...] # list with 10000 random uppercase letters


def test1():
    return list(map(operator.concat, lst[:-1], lst[1:]))


def test2():
    return [x + y for x, y in zip(lst, lst[1:])]


def test3():
    return [v + lst[i + 1] for i, v in enumerate(lst[:-1])]


def test4():
    s = ''.join(lst)
    return [s[i:i + 2] for i in range(len(s) - 1)]


if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test1()", setup="from __main__ import test1, lst", number=10000))
    print(timeit.timeit("test2()", setup="from __main__ import test2, lst", number=10000))
    print(timeit.timeit("test3()", setup="from __main__ import test3, lst", number=10000))
    print(timeit.timeit("test4()", setup="from __main__ import test4, lst", number=10000))
Run Code Online (Sandbox Code Playgroud)

结果:

  1. Python 2:

    10.447159509
    11.529946446
    20.962497298000002
    20.515838672
    
    Run Code Online (Sandbox Code Playgroud)
  2. Python 3:

    10.370675522
    11.429417197
    20.836504865999995
    20.422865353
    
    Run Code Online (Sandbox Code Playgroud)

在更大的数据map()是有点(〜9%)快,但有之间没有显著差异test1()test2()