我正在创建一个函数,它返回一个显示布尔值的元组

2024-06-13 22:50:39 发布

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

如果列表中的元素是回文还是非回文,我必须创建一个显示True或False的程序

我已经创建了第一部分

    def es_palindromo(texto):
    rta = ""
    for i in range(len(texto)):
        rta += texto[i]
    if (rta == texto):
        print(True)
    elif (rta != texto):
        print(False)
    return rta
es_palindromo("bob")

现在,我正在尝试创建一个新函数,它向我显示回文单词的数量和那些没有回文单词的数量。应该在一个元组上,并给出类似于:(1, 2[True, False, True])的内容,列表将是

list = ["oso","hola","bob"]

Tags: 程序falsetrue元素列表for数量es
2条回答

首先,在您的代码中存在缩进问题,而且您期望的输出在python中无效。但是,下面的代码将返回一个元组,第一个元素作为回文字符串的数量,第二个元素作为列表,说明输入列表中给定的字符串是否为回文字符串

list1 = ["oso","hola","bob"] #list variable
def es_palindromo(texto):
    if texto == texto[::-1]:
        return True
    else:
        return False

def return_tuple(input_list):
    count = 0
    ans = []
    for i in list1:
        if es_palindromo(i):
            count+=1
            ans.append(return_tuple(i))
    return (count,ans)

return_tuple(list1)

如果你的文本是以列表的形式出现的,你可以直接访问这些项目。试试这个

def es_palindromo(texto):
    ans= [True if x ==x[::-1] else False for x in texto]
    count = [ans.count(i) for i in set(ans) ]
    print(count)
    return (count,ans)

相关问题 更多 >