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

在Python列表中合并一些列表项,python,list,concatenation,Python,List,Concatenation,假设我有这样一个列表: [a, b, c, d, e, f, g] 如何修改该列表,使其看起来像这样 [a, b, c, def, g] items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] items[3:6] = [''.join(items[3:6])] 我更希望它直接修改现有列表,而不是创建新列表 这个例子很模糊,但可能是这样的 [a, b, c, def, g] items = ['a', 'b', 'c', 'd', 'e', 'f

假设我有这样一个列表:

[a, b, c, d, e, f, g]
如何修改该列表,使其看起来像这样

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

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

这个例子很模糊,但可能是这样的

[a, b, c, def, g]
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]
它基本上执行拼接(或)操作。它删除项目3到6,并在其位置插入一个新列表(在本例中,是一个包含一个项目的列表,它是已删除的三个项目的串联。)

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


这使用了一个函数,该函数基本上使用
+
运算符将项目添加到一起。

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

查看上的文档,特别是上的。也许还可以。

我的心灵感应能力不是特别强,但我想你想要的是:

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
我应该注意到,因为这可能并不明显,它与其他答案中提出的不一样。

只是一个变体

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']

合并的依据是什么?a、b等是什么(即什么数据类型)?目前,在Python解释器中键入此项会出现错误,因为这些是未绑定的名称。您总是希望将列表中的这些项串联起来,还是希望能够选择以后的位置和数量?这对于字符串列表非常有用。如果元素不是字符串,则需要使用“”以外的其他内容。join()没错,我添加了一个使用
reduce
的示例,该示例适用于支持
+
运算符的任何类型的项。我不能做更多的事情,除非OP对他的问题进行扩展。他的问题对字符串以外的任何东西都没有意义。使用reduce对通用解决方案投了赞成票-虽然这个问题似乎只对字符串有意义,但将列表中的所有元素相互追加的通用解决方案是一个很好的解决方案。