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.
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.
这个例子很模糊,但也许是这样的?
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])]
只是一个变化
alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist
当然@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']
我的心灵感应能力不是特别好,但这是我认为你想要的:
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
我应该注意,因为它可能并不明显,它与其他答案中提出的不同。