我有兩個列表——其中一個是字符串列表,另一個是嵌套的字符串列表。我想在兩個列表之間的交點之后保存字符串列表中的下 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
添加回答
舉報
0/150
提交
取消