亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

與另一個列表比較后保存列表中的后續項目

與另一個列表比較后保存列表中的后續項目

SMILET 2023-10-11 20:06:36
我有兩個列表——其中一個是字符串列表,另一個是嵌套的字符串列表。我想在兩個列表之間的交點之后保存字符串列表中的下 5 個項目。例如,這是我有的兩個列表:list1 = [['this', 'is', 'the', 'common', 'part'], ['this', 'is', 'another', 'commonality']]list2 = ['this', 'is', 'the', 'common', 'part', 'and', 'i', 'am', 'saving', 'this', 'blah', 'blah', 'this', 'is', 'another', 'commonality', 'i', 'am', 'also', 'saving', 'this']期望的輸出是:result = [['and', 'i', 'am', 'saving', 'this'], ['i', 'am', 'also', 'saving', 'this']]我的代碼有許多不友好的嵌套條件——如果有人有一個干凈的方法來實現目標,我將不勝感激!
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

你可以這樣嘗試:


amount_of_subsequent_items = 5

result = []

for sublist in list1:

    for i in range(len(list2)-1):

        if sublist == list2[i:i+len(sublist)]:

            result.append(list2[i+len(sublist):i+len(sublist)+amount_of_subsequent_items])

這通過在 中的任何位置list1查找sublist(of ) 的出現來迭代您的。如果發現某個事件,則包含 的下一個后續項目的列表將存儲在 中。list1list2amount_of_subsequent_itemslist2result


查看完整回答
反對 回復 2023-10-11
  • 1 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號