我正在嘗試查找字符串列表中是否存在子字符串,例如:我有單詞列表 ['GGBASDEPINK','ASDEKNIP','PINK','WORDRRAB','BAR']PINK 是 ASDEKNIP 的一個子串,因為 PINK 的反面是 KNIP 而單詞 BAR 在 WORDRRAB 中,因為反面是 RAB如何查找子帶是否退出?如果是,那么把那個字符串倒過來,這樣新列表應該是:d = ['GGBASDEPINK','ASDEKNIP','PINK','WORDRRAB','BAR' ,'KNIP', 'RAB']我試過這樣d = ['GGBASDEPINK','ASDEKNIP','PINK','WORDRRAB','BAR']for word in d: word = word[::-1] if word in d: print(word)但它什么也沒給
1 回答

月關寶盒
TA貢獻1772條經驗 獲得超5個贊
使用itertools.permutations:
from itertools import permutations
d = ['GGBASDEPINK','ASDEKNIP','PINK','WORDRRAB','BAR']
for x, y in permutations(d, 2):
rev = y[::-1]
if rev in x:
d.append(rev)
print(d)
# ['GGBASDEPINK', 'ASDEKNIP', 'PINK', 'WORDRRAB', 'BAR', 'KNIP', 'RAB']
添加回答
舉報
0/150
提交
取消