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

标签 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)

更新

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

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 是为了不将单个单词回文视为匹配项。

关于python - 如何将字符串列表中的反向字符串与python中的原始字符串列表进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497690/

相关文章:

python - Pandas 根据多行和条件进行计算

Python:将请求置于休息 api 发送 Bad request 400 错误

python - Hadoop Streaming Python 简单示例不起作用

CentOS 上的 python 升级

python - 使用 pySpark 计算月末差异

python - Flask-SQLAlchemy 中的 LocalProxy 对象

python - tweepy OAuthHandler 出错

python - 导入错误 : No module named flask_restful

python : Detect Color Then Click Color

python - 使用 os.remove() 时,每 10000 次左右就有 1 次出现 PermissionError