46

Say I have a list like this:

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

How do modify that list so that it looks like this?

[a, b, c, def, g]

I would much prefer that it modified the existing list directly, not created a new list.

4

5 回答 5

69

合并应该在什么基础上进行?你的问题比较模糊。另外,我假设 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']

查看关于序列类型的文档,特别是关于可变序列类型的文档。也许还有关于字符串方法

于 2009-07-17T12:08:15.267 回答
41

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

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

它基本上执行拼接(或分配给切片)操作。它删除项目 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基本上使用+运算符将​​项目添加在一起的函数。

于 2009-07-17T12:07:51.757 回答
5

只是一个变化

alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist
于 2009-07-17T12:43:12.957 回答
1

当然@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']
于 2019-03-20T22:51:44.623 回答
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

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

于 2009-07-17T12:12:36.363 回答