假设我有一个像这样的列表:
[a, b, c, d, e, f, g]
如何修改那个列表,使其看起来像这样?[a, b, c, def, g]
我更喜欢它直接修改现有的列表,而不是创建一个新列表。
假设我有一个像这样的列表:
[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])]
这基本上执行了一个splice(或对于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
的示例,可以适用于任何支持 +
运算符的类型。除非提问者进一步扩展问题,否则我无法再做更多的工作。 - Blixt只是一种变化
alist=["a", "b", "c", "d", "e", 0, "g"]
alist[3:6] = [''.join(map(str,alist[3:6]))]
print alist
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