str对象不可调用错误python

时间:2018-01-06 23:40:45

标签: python

我一直试图在Python中运行以下代码:

def likes(names):
    dictionary_of_sizes = {
        0:"no one likes this", 
        1:(lambda names: "{} likes this".format(names[0])),
        2:(lambda names: "{} and {} like this".format(names[0], names[1])),
        3:(lambda names: "{}, {} and {} like this".format(name[0], names[1],names[2])),
        4:(lambda names: "{}, {} and {} others like this".format(names[0], names[1], len(names)-2))
    }
    return dictionary_of_sizes[len(names)](names) if len(names)<4 else dictionary_of_sizes[4]

我总是得到错误&#39; str&#39;对象不可调用。

问题:我做错了什么?

2 个答案:

答案 0 :(得分:2)

如果传递一个空字符串,它会写出错误信息。 您可以使用列表而不是字典:

def likes(names):
    options = ["no one likes this", 
                lambda names: "{} likes this".format(names[0]),
                lambda names: "{} and {} like this".format(names[0], names[1]),
                lambda names: "{}, {} and {} like this".format(name[0], names[1],names[2]),
                lambda names: "{}, {} and {} others like this".format(names[0], names[1], len(names)-2)
            ]
    if type(names) == list:
        return options[min(len(options),len(names))](names)

使用Python 3.6的f-strings:

def likes(names):
    options = [ lambda:"no one likes this", 
                lambda:f"{names[0]} likes this",
                lambda:f"{names[0]} and {names[1]} like this",
                lambda:f"{names[0]}, {names[1]} and {names[2]} like this",
                lambda:f"{names[0]}, {names[1]} and {len(names)-2} others like this"
            ]
    return options[min(len(options),len(names))]()


print(likes([]))
print(likes("bob"))
print(likes([""]))
print(likes(["alice","bob"]))
print(likes(["alice","bob","charlie"]))
print(likes(["alice","bob","charlie","david"]))

输出:

no one likes this
no one likes this
b, o and b like this
 likes this
alice and bob like this
alice, bob and charlie like this
alice, bob and 2 others like this

答案 1 :(得分:1)

您没有向我们展示抛出异常的代码。当你不告诉我们你在做什么时,很难说出你做错了什么。但如果我这样做,它似乎有效:

>>> likes(["John","Harry"])
'John and Harry like this'

我怀疑你可能会这样打likes()

>>> likes(["John","Harry"])()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'str' object is not callable

或者像这样:

>>> likes("")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 7, in likes
TypeError: 'str' object is not callable

您在解决如何调用该功能时遇到麻烦并不奇怪。对于它所做的事情,代码是不必要的复杂。它需要完全重写。如果您想快速修复,请更改以下行:

{0:"no one likes this", 

{0:(lambda names: "no one likes this"),

但你应该放弃所有那些不必要且难以阅读的lambda并执行以下操作:

def likes(names):
    if len(names) > 3:
        names = names[:2] + [f"{len(names)-2} others"]
    elif len(names) == 0:
        names = ["no-one"]
    result = " and ".join(", ".join(names).rsplit(", ",1))
    if len(names) == 1:
        return result + " likes this"
    else:
        return result + " like this"