用python中的另一个子列表替换子列表

时间:2012-10-15 14:41:19

标签: python list

我想将列表a中的子列表替换为另一个子列表。像这样:

a=[1,3,5,10,13]

让我们说我想要一个子列表:

a_sub=[3,5,10]

并将其替换为

b_sub=[9,7]

所以最终结果将是

print(a) 
>>> [1,9,7,13]

有什么建议吗?

4 个答案:

答案 0 :(得分:12)

In [39]: a=[1,3,5,10,13]

In [40]: sub_list_start = 1

In [41]: sub_list_end = 3

In [42]: a[sub_list_start : sub_list_end+1] = [9,7]

In [43]: a
Out[43]: [1, 9, 7, 13]

希望有所帮助

答案 1 :(得分:11)

您可以使用列表切片很好地完成此任务:

>>> a=[1, 3, 5, 10, 13]
>>> a[1:4] = [9, 7]
>>> a
[1, 9, 7, 13]

那么我们如何在这里得到指数呢?好吧,让我们从找到第一个开始吧。我们逐项扫描,直到找到匹配的子列表,并返回该子列表的开头和结尾。

def find_first_sublist(seq, sublist, start=0):
    length = len(sublist)
    for index in range(start, len(seq)):
        if seq[index:index+length] == sublist:
            return index, index+length

我们现在可以进行更换 - 我们从头开始,更换我们找到的第一个,然后在我们新完成更换后尝试找到另一个。我们重复这个,直到我们再也找不到要替换的子列表。

def replace_sublist(seq, sublist, replacement):
    length = len(replacement)
    index = 0
    for start, end in iter(lambda: find_first_sublist(seq, sublist, index), None):
        seq[start:end] = replacement
        index = start + length

我们可以很好地使用:

>>> a=[1, 3, 5, 10, 13]
>>> replace_sublist(a, [3, 5, 10], [9, 7])
>>> a
[1, 9, 7, 13]

答案 2 :(得分:1)

您需要从start_index切换到end_index + 1,并将子列表分配给它。

就像您可以这样做: - a[0] = 5,您可以同样为您的slice分配一个子列表: - a[0:5] - >从index 0 to index 4

创建切片

您只需找出要替换的position的{​​{1}}。

sublist

正如您所看到的,>>> a=[1,3,5,10,13] >>> b_sub = [9, 7] >>> a[1:4] = [9,7] # Substitute `slice` from 1 to 3 with the given list >>> a [1, 9, 7, 13] >>> 子列表不必与substituted子列表的长度相同。

实际上你可以用2个长度列表替换4个长度列表,反之亦然。

答案 3 :(得分:0)

这是另一种方法。如果我们需要替换多个子列表,则此方法有效:

a=[1,3,5,10,13]
a_sub=[3,5,10]
b_sub=[9,7]

def replace_sub(a, a_sub, b_sub):
    a_str = ',' + ','.join(map(str, a)) + ','
    a_sub_str = ',' + ','.join(map(str, a_sub)) + ','
    b_sub_str = ',' + ','.join(map(str, b_sub)) +','

    replaced_str = a_str.replace(a_sub_str, b_sub_str)[1 : -1]

    return map(int, replaced_str.split(','))

结果:

>>> replace_sub(a, a_sub, b_sub)
[1, 9, 7, 13]
>>> replace_sub([10, 13, 4], [3, 4], [7])
[10, 13, 4] #[3,4] is not in the list so nothing happens

替换多个子列表:

>>> a=[1,3,5,10,13,3,5,10]
>>> a_sub=[3,5,10]
>>> b_sub=[9,7]
>>> replace_sub(a, a_sub, b_sub)
[1, 9, 7, 13, 9, 7]