others - 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反转出现在同一个字符串中)

时间:

你几乎做到了,只需要添加另一个循环,来比较每个单词与反序的单词。 尝试使用以下


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)




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'}


str = input()


x = str.split()


y = []


while len(x) > 0 :


 a = x.pop(0)


 if a[::-1] in x:


 y.append(a)



print(y) # ['is']



另一种方法是在列表推导中执行这个操作:


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



 

: )

...