簡體   English   中英

Python 在列表中查找並保留模式並替換其他模式

[英]Python find and keep patterns in a list and replace others

我正在嘗試編寫代碼以從列表列表中的每個列表中提取模式。 我搜索具有指定長度的模式,例如“B-”后跟“I-”。 例如,我想保留長度為 2 的模式,並用以下列表中的指定字符串替換其他模式:

list = ['O', 'B-', 'I-', 'I-', 'O', 'B-', 'I-', 'B-']

預期的 output 應如下所示:

expected_list_2 = ['O', 'O', 'O', 'O', 'O', 'B-', 'I-', 'O']

可以看出只有兩個模式“B-”的長度,“I-”被保留,其他的被“O”label改變。

如果我想保留長度為 3 的模式,則 output 應如下所示:

expected_list_3 = ['O', 'B-', 'I-', 'I-', 'O', 'O', 'O', 'O']

考慮到我的列表列表中的每個元素都包含此類列表,並且我嘗試為每個列表實現此任務,我問,是否有任何有效或棘手的方法來執行此操作,而不是定義一些 if-else 條件並循環每個元素?

該解決方案應該(請在部署到生產之前使用更多相關案例進行測試)在list中找到模式 'B-', n-1 x 'I-' 的所有位置。 我擴展了示例list1以涵蓋更多情況,例如列表開頭和結尾的模式以及連續模式

list1 = ['B-', 'I-', 'I-', 'O', 'B-', 'I-', 'I-', 'B-', 'I-', 'B-', 'I-', 'O', 'B-', 'I-', 'I-']
#n = 2:                                            ^^^^^^^^^   ^^^^^^^^^
#n = 3:  ^^^^^^^^^^^^^^^^        ^^^^^^^^^^^^^^^                                ^^^^^^^^^^^^^^^

def find_pattern(list1, n):
    pattern = ['B-'] + ['I-'] * (n-1)
    first = pattern[0]
    
    # find starting indices of matching patterns
    idx = [e for e, i in enumerate(list1[:-n+1])
             if i == first                   # optimization for long pattern
            and list1[e:e+n] == pattern
            and list1[e+n:e+n+1] != ['I-']]

    # insert pattern at those indices
    res = ['O'] * len(list1)
    for i in idx:
        res[i:i+n] = pattern 
    return res

print(find_pattern(list1, 2))
print(find_pattern(list1, 3))

Output

['O', 'O', 'O', 'O', 'O', 'O', 'O', 'B-', 'I-', 'B-', 'I-', 'O', 'O', 'O', 'O']
['B-', 'I-', 'I-', 'O', 'B-', 'I-', 'I-', 'O', 'O', 'O', 'O', 'O', 'B-', 'I-', 'I-']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM