“int”对象是不可iterable的,两个代码之间的区别是什么?

2024-04-24 19:03:08 发布

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

我想算出字符串中最短单词的长度 这是我的密码:

def find_short(s):
    for x in s.split():
        return min (len(x))

正确的方法是:

def find_short(s):
    return min(len(x) for x in s.split())

那么我的代码和正确的代码有什么区别呢?哪段代码是不可编辑的?你知道吗


Tags: 方法字符串代码in密码forlenreturn
3条回答

min()接受一个序列,并返回该序列中最小的项。你知道吗

len()获取一个序列,并返回单个长度(该序列的长度)。你知道吗

您的第一个代码对每个长度调用min()。。。这没有意义,因为min()需要一个序列作为输入。你知道吗

输入:你的问题是什么

def find_short(s):
    for x in s.split(): # here s.split() generates a list [what, is, your, question]
        return min(len(x)) # you will pass the length of the first element because you're only passing length of one word len(what) to min and immediately trying to return.

您需要将iterable项传递给min function not int type

哪里和这里一样

def find_short(s):
    return min(len(x) for x in s.split())
 #here there are three nested operations:
 #1. split the string into list s.split() [what, is, your, question] 
 #2. loop the list and find the length of each word by len(x) and put it into a tuple compression (4, 2, 4, 8)
 #3. pass that tuple compression to the min function min((4, 2, 4, 8))
 # and lastly return the smallest element from tuple

可能是错的,但我猜你是返回最小长度的x为每x。。。你知道吗

相关问题 更多 >