簡體   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