使用函数在列表中比较回文字符串

2024-05-23 14:46:03 发布

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

嗨,我有一个列表中的字符串项目列表。我想看看这些字符串中的单词是否是使用函数的回文。 到目前为止我已经得到了这个密码

input_list = ['taco cat', 'bob', 'davey']
def palindromes(x):
    for x in input_list:
        if x == x[::-1]
            return True
        else:
            return False 
output = [palindromes(x)]
print(output)

结果应在列表中[真、真、假] 我在这里做错了什么


Tags: 项目函数字符串密码列表inputoutputreturn
3条回答

您可能应该简化palindromes函数,以便只处理单个字符串:

def palindrome(x):
    x = x.replace(" ", "")  # given your sample data
    return x == x[::-1]

然后使用理解:

output = [palindrome(x) for x in input_list]

或者,使用map

output = [*map(palindrome, input_list)]

尝试:

input_list = ['taco cat', 'bob', 'davey']
def palindromes(x):
   x_no_spaces = x.replace(' ', '')
   return x_no_spaces == x_no_spaces[::-1]

print([palindromes(i) for i in input_list]

试试这个:

input_list = ['taco cat', 'bob', 'davey']


def palindromes(x):
    return x == x[::-1]


output = [palindromes(x) for x in input_list]
print(output)

[False, True, False]

相关问题 更多 >