我有以下字串串列:
my_list1 = [' If the display is not working ', "<xxx - tutorial section>", "tutorial section", ' display message appears. ']
my_list2 = [' If the display is not working ', "tutorial section", "<xxx - tutorial section>", ' display message appears. ']
如何識別一個字串,該字串等于緊隨其后或之前由和符號-包圍的子字串。在我的示例中,這是. 我想洗掉此字串以獲得以下結果:<>tutorial section
my_list1_ed = [' If the display is not working ', "<xxx - tutorial section>", ' display message appears. ']
my_list2_ed = [' If the display is not working ', "<xxx - tutorial section>", ' display message appears. ']
如果串列不包含此類重復項,則不應執行任何操作。我該如何實作這個邏輯?
我的嘗試:
final_list = []
lists = my_list1 my_list2
for i, v in enumerate(lists):
if (v not in lists[i-1]) or (v not in lists[i 1]):
final_list.append(v)
我得到的結果(重復仍然存在):
[' If the display is not working ',
'<xxx - tutorial section>',
'tutorial section',
' display message appears. ',
' If the display is not working ',
'tutorial section',
'<xxx - tutorial section>',
' display message appears. ']
uj5u.com熱心網友回復:
稍微改了一下代碼,看看有沒有幫助。
final_list = []
lists = my_list1 my_list2
for i, v in enumerate(lists):
if i == 0:
if v not in lists[i 1]:
final_list.append(v)
elif i == len(lists) - 1:
if v not in lists[i-1]:
final_list.append(v)
else:
if (v not in lists[i-1]) and (v not in lists[i 1]):
final_list.append(v)
print(final_list)
輸出:[' If the display is not working ', '<xxx - tutorial section>', ' display message appears. ', ' If the display is not working ', '<xxx - tutorial section>', ' display message appears. ']
uj5u.com熱心網友回復:
我將這樣做。
my_list1 = [' If the display is not working ', "<xxx - tutorial section>", "tutorial section", ' display message appears. ']
my_list2 = [' If the display is not working ', "tutorial section", "<xxx - tutorial section>", ' display message appears. ']
all_l = []
new_list1 = []
new_list2 = []
matches = ['-','<','>']
for i in range(len(my_list1)):
if any(x in my_list1[i] for x in matches):
nl1 = [r for r in my_list1 if not r in my_list1[i] or r == my_list1[i]]
new_list1 = nl1
if any(x in my_list2[i] for x in matches):
nl2 = [r for r in my_list2 if not r in my_list2[i] or r == my_list2[i]]
new_list2 = nl2
print(new_list1)
print(new_list2)
輸出:
[' If the display is not working ', '<xxx - tutorial section>', ' display message appears. ']
[' If the display is not working ', '<xxx - tutorial section>', ' display message appears. ']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/478125.html
