[英]How to compare reverse strings in list of strings with the original list of strings in 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'的反轉出現在同一個字符串中)
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()
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
是為了不考慮單個單詞回文匹配。
另一種方法是在列表理解中:
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
列表中理解和引用相同的列表。 :)
這個答案不會顯示你'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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.