如何将字符串列表中的反向字符串与python中的原始字符串列表进行比较?

时间:2019-06-07 15:53:05

标签: python

输入给定的字符串,并检查该字符串中是否有与之相反的单词,然后打印该单词,否则打印$

我将字符串拆分并将单词放入列表中,然后反转该列表中的单词。之后,我无法比较两个列表。

str = input()
x = str.split()
for i in x: # printing i shows the words in the list
    str1 = i[::-1] # printing str1 shows the reverse of words in a new list
    # now how to check if any word of the new list matches to any word of the old list 
    if(i==str):
        print(i)
        break
    else:
        print('$)

输入:suman is a si boy

输出:is(由于在同一字符串中存在“ is”的反面)

4 个答案:

答案 0 :(得分:1)

a = 'suman is a si boy'

# Construct the list of words
words = a.split(' ')

# Construct the list of reversed words
reversed_words = [word[::-1] for word in words]

# Get an intersection of these lists converted to sets
print(set(words) & set(reversed_words))

将打印:

  

{'si', 'is', 'a'}

答案 1 :(得分:1)

您几乎拥有了它,只需要添加另一个循环就可以将每个单词与每个反向单词进行比较。尝试使用以下

str = input()
x = str.split()
for i in x:
    str1 = i[::-1]
    for j in x: # <-- this is the new nested loop you are missing
        if j == str1: # compare each inverted word against each regular word
            if len(str1) > 1: # Potential condition if you would like to not include single letter words
                print(i)

更新

要仅打印第一次出现的匹配项,可以在第二个循环中仅检查后面的元素。我们可以通过跟踪索引来做到这一点:

str = input()
x = str.split()
for index, i in enumerate(x):
    str1 = i[::-1]
    for j in x[index+1:]: # <-- only consider words that are ahead
        if j == str1: 
            if len(str1) > 1: 
                print(i)

请注意,我使用index+1是为了不将单个单词回文词视为匹配项。

答案 2 :(得分:1)

另一种方法是通过列表理解:

string = 'suman is a si boy'  

output = [x for x in string.split() if x[::-1] in string.split()]

print(output)

按字符串拆分会创建一个按空格拆分的列表。然后,仅当字符串中包含反向字符时,才包含单词。

输出为:

['is', 'a', 'si']

一个便笺,您有一个变量名str。最好不要这样做,因为str是Python的事情,以后可能会在代码中引起其他问题。

如果您想要的单词长度不止一个字母,那么您可以这样做:

string = 'suman is a si boy'

output = [x for x in string.split() if x[::-1] in string.split() and len(x) > 1]

print(output)

这给出了:

['is', 'si']

最终答案...

最后要想的是,为了得到'is'

string = 'suman is a si boy'

seen = []
output = [x for x in string.split() if x[::-1] not in seen and not seen.append(x) and x[::-1] in string.split() and len(x) > 1]                      

print(output)

输出为:

['is']

但是,我认为这不一定是一个好方法。基本上,您是在列表理解期间在seen 中存储信息,并引用同一列表。 :)

答案 3 :(得分:0)

此答案不会显示'a',也不会输出'is'和'si'。

str = input() #get input string
x = str.split() #returns list of words
y = [] #list of words
while len(x) > 0 :
    a = x.pop(0) #removes first item from list and returns it, then assigns it to a
    if a[::-1] in x: #checks if the reversed word is in the list of words
                     #the list doesn't contain that word anymore so 'a' that doesn't show twice wouldn't be returned
                     #and 'is' that is present with 'si' will be evaluated once

        y.append(a)

print(y) # ['is']
相关问题