繁体   English   中英

如何在单词列表中查找子字符串

[英]How to find substrings in a list of words

我正在尝试查找字符串列表中是否存在子字符串,例如:

我有单词列表['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)

却什么也没有

使用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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM