繁体   English   中英

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

[英]Replacing a sublist with another sublist in python

我想用另一个子列表替换列表a子列表。 像这样的东西:

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

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

a_sub=[3,5,10]

并替换它

b_sub=[9,7]

所以最终的结果将是

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

有什么建议?

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]

希望有所帮助

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

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

您需要从start_indexend_index + 1进行切片,并将子列表分配给它。

就像你可以这样做: - a[0] = 5 ,你可以类似地为你的slice分配一个子列表: - a[0:5] - >创建一个从index 0 to index 4的切片

您所需要的只是找出要替换的sublistposition

>>> 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子列表不必与substituting子列表的长度相同。

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

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

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM