将列表中的字符串相加

12
我希望将列表["A","B","A","A","B"]转换为列表["AB","BA","AA","AB"]
我尝试定义一个新的列表,首先删除第一个元素,然后将列表的字符串连接在一起。之后,我计划删除新列表的最后一个元素以获得结果。
lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]

但我得到的全部是

TypeError: 'list'对象不能被解释为整数

欢迎任何帮助。

编辑:谢谢大家,你们的所有解决方案都完美地解决了问题 :)

4个回答

14

最佳解决方案,使用带有列表推导的zip,是最巧妙的:

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

或者使用带有列表推导式的enumerate

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

13

使用 zip()

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

8
你可以使用 map()
s = list(map(str.__add__, lst[:-1], lst[1:]))

建议使用operator.concat(),这样会更好一些(感谢@MykolaZotko的建议):

import operator

s = list(map(operator.concat, lst[:-1], lst[1:]))

更新。

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

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))

结果:

  1. Python 2:

    10.447159509
    11.529946446
    20.962497298000002
    20.515838672
    
  2. Python 3:

    10.370675522
    11.429417197
    20.836504865999995
    20.422865353
    

在较大的数据集中,map() 方法会稍微快一些(约 9%),但是 test1()test2() 之间没有显著差异。


1
你也可以使用 operator.addoperator.concat。奇怪的是,map 更快。通常情况下,map 比列表推导式更慢。 - Mykola Zotko
@MykolaZotko,它并不更快,几毫秒慢点,几乎一样。我在复制数据时犯了个错误。 - Olvin Roght

4

您的原始代码存在几个问题:

sequences = ["A","B","A","A","B"]
lista = sequences
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]

首先,语句 lista = sequences 并没有复制 sequences。相反,listasequences 成为同一个列表的两个不同名称。使用一个名称所做的操作也会发生在另一个名称上。lista.pop(0)sequences.pop(0) 是相同的。如果您想要一份副本,请导入 copy 库。
import copy

sequences = ["A","B","A","A","B"]
lista = copy.copy(sequences)
lista.pop(0)
print(lista)

for x in range(sequences):
    mc =sequences[x]+lista[x]

其次,你的语句 range(sequences) 是不正确的。 range() 函数接受整数作为输入,而不是列表。 这就导致了 TypeError: 'list' object cannot be interpreted as an integer 的错误提示。
# VALID
range(5)
range(3)
range(10)

# INVALID
range(["A","B","A"])
range(["eyes", "nose", "tail"])

sequences是一个列表。你需要使用range(len(sequences))而不是range(sequences)

最终,我们可以修改你的原始代码以使其正常工作:

import copy

sequences = ["A","B","A","A","B"]
lista = copy.copy(sequences)
lista.pop(0)
print(lista) # prints ["B","A","A","B"]

mc = list()
for x in range(len(lista)):
    mc.append(lista[x] + sequences[x + 1])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接