查找单词列表是否包含单词的倒数

2024-06-28 18:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

给出一个列表,例如

['table', 'drawer', 'chair', 'reward', 'radar']

如何创建一个函数/for循环,以返回列表中有其相反方向的单词的列表?我试图只包含给定单词的第一个实例

因此,结果将是:

['drawer', 'radar']

而不是

['drawer','reward', 'radar']

到目前为止,我的代码返回后一个结果:

def find_reversals(lst):

    emptylst = []
    match = []

    for word in lst:
        new = word[::-1]
        emptylst.append(new)

    for i in lst:
        for j in emptylst:
            if i == j:
                match.append(i)

    print('{}'.format(match))

Tags: in列表newformatchtable单词word
3条回答

您可以执行以下操作:

lst = ['table', 'drawer', 'chair', 'reward', 'radar']
s = set(lst)

result = []
for word in lst:
    reverse = word[::-1]
    if reverse in s:
        result.append(word)
    s.remove(word)

print(result)

输出

['drawer', 'radar']

由于它使用一个集合,复杂性为O(n),其中n是列表中的元素数

这是一个没有集合的解决方案,有多个for循环:

lst = ['table', 'drawer', 'chair', 'reward', 'radar']
result = []

for e in lst:
    new_word = e[::-1]    #Make a reverse of a word
    if new_word in lst:
        if e not in result and e[::-1] not in result:    #Check if the word, or a reversed word is in the list, and if not, put it in a list
            result.append(e)

print(result)

您可以使用两个索引来迭代列表,ij,其中ji开始(只要您希望回文计数)

found = set()
a = ['table', 'drawer', 'chair', 'reward', 'radar']
ret = []
for i in range(len(a)): 
    for j in range(i, len(a)): 
       if a[j][::-1] == a[i]: 
           word = ''.join(sorted(a[i])) 
           if word not in found: 
               found.add(word) 
               ret.append(a[i])

# ret = ['drawer', 'radar']

你重复计算的原因是因为你没有跟踪是否发现了什么东西。在本例中,我通过set和该单词的排序顺序来跟踪它

相关问题 更多 >