合并Python列表中的一些列表项

时间:2009-07-17 12:03:06

标签: python list concatenation

说我有这样的清单:

[a, b, c, d, e, f, g]

如何修改该列表以使其看起来像这样?

[a, b, c, def, g]

我更希望它直接修改现有列表,而不是创建新列表。

5 个答案:

答案 0 :(得分:48)

合并的基础是什么?你的问题很模糊。另外,我假设a,b,...,f应该是字符串,即'a','b',...,'f'。

>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> x[3:6] = [''.join(x[3:6])]
>>> x
['a', 'b', 'c', 'def', 'g']

查看sequence types上的文档,特别是mutable sequence types上的文档。也许也在string methods上。

答案 1 :(得分:32)

这个例子很模糊,但也许是这样的?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

它基本上执行拼接(或assignment to a slice)操作。它删除了第3到第6项并在其位置插入了一个新列表(在这种情况下是一个包​​含一个项目的列表,这是已删除的三个项目的串联。)

对于任何类型的列表,您都可以这样做(对所有项目使用+运算符,无论其类型是什么):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

这使用reduce函数和lambda函数,它基本上使用+运算符将项目添加到一起。

答案 2 :(得分:5)

只是变种

alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist

答案 3 :(得分:0)

我的心灵感应能力并不是特别好,但这就是我认为你想要的:

def merge(list_of_strings, indices):
    list_of_strings[indices[0]] = ''.join(list_of_strings[i] for i in indices)
    list_of_strings = [s for i, s in enumerate(list_of_strings) if i not in indices[1:]]
    return list_of_strings

我应该注意,因为它可能并不明显,它与其他答案中提出的不一样。

答案 4 :(得分:0)

当然,@ Stephan202给出了一个非常好的答案。我提供了一种替代方法。

def compressx(min_index = 3, max_index = 6, x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']):
    x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
    return x
compressx()

>>>['a', 'b', 'c', 'def', 'g']

您还可以执行以下操作。

x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
print(x)

>>>['a', 'b', 'c', 'def', 'g']
相关问题