Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,在';int';和';str';错误_Python - Fatal编程技术网

Python,在';int';和';str';错误

Python,在';int';和';str';错误,python,Python,这是我的功能 def find_short(s): s = s.split() max = len(s[0]) for i in s: if len(i) <= max: max = i return max print(find_short("bitcoin take over the world maybe who knows perhaps")) def find_short(s)

这是我的功能

def find_short(s):
    s = s.split()
    max = len(s[0])
    for i in s:
        if len(i) <= max:
            max = i
    return max

    print(find_short("bitcoin take over the world maybe who knows perhaps"))
def find_short(s):
s=s.split()
max=len(s[0])
对于s中的i:

如果len(i),那是因为
max=i
行使
max
变量成为
字符串。无法比较
字符串
int
值。这是因为您将
i
分配给
max
变量
s
的一个元素
i
时忘记了在
for
循环中为
i
添加一些
len
。请参阅我纠正此错误的答案

def find_short(s):
    s = s.split()
    if not s:
       return 0,""
    max = len(s[0])
    argmax = s[0]
    for i in s:
        if len(i) <= max:
            max = len(i)
            argmax = i
    return max,argmax

print(find_short("bitcoin take over the world maybe who knows perhaps"))
(3, 'who')
def find_short(s):
s=s.split()
如果不是,则:
返回0“
max=len(s[0])
argmax=s[0]
对于s中的i:

如果len(i)在上述代码中,您犯了两个错误

  • 使用max时,max是python的一个内置函数,因此请使用其他名称,如maxi

  • 最后,在if类中的第一个条件检查之后,如果条件满足max(u使用的),将使用字符串i进行更新,如果要在字符串中打印小写字母,请使用以下代码

     def find_short(s):
         s = s.split()
         maxi = len(s[0])
         for i in s:
             if len(i) <= maxi:
                 maxi = len(i)
                 ans = i
         return len(ans)
     print(find_short("bitcoin take over the world maybe who knows perhaps"))
    
     def find_short(s):
         s = s.split()
         maxi = len(s[0])
         for i in s:
             if len(i) <= maxi:
                 maxi = len(i)
                 ans = i
         return len(ans)
     print(find_short("bitcoin take over the world maybe who knows perhaps"))
    
    def find_short(s):
    s=s.split()
    maxi=len(s[0])
    对于s中的i:
    
    如果len(i)请将您的代码格式化为有效的Python代码(例如现在
    def…
    s=…
    具有相同的意图),您应该执行max=len(i)而不是max=i,因为我在你的代码中是一个字符串。是的,我会的,但它说8分钟后Hanks dude帮了我一把,我添加了一个
    if语句来处理
    空的
    字符串大小写。编程就是考虑所有最坏的情况:)。由于我们处于Python>3.8时代,我建议使用walrus操作符()来避免调用
    len()
    两次
    if(n:=len(i))调用
    len
    ,至少对于
    列表对象之类的内置类型。