2017-02-19 57 views
-3

我想弄清楚一个字符串 这里最短单词的长度是我的代码:'int'对象不可迭代和两个代码之间的区别?

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()) 

有啥我的代码和正确之间的差异?哪段代码是不可迭代的?

回答

2

min()需要一个序列,并返回该序列中的最小项目。

len()取一个序列,并返回一个单一的长度(该序列的长度)。

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

0

也许错了,但我的猜测是,你正在返回x的最小长度为每x ...

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

这里,x包含individul话。对于每一次迭代,您将在x中得到一个新单词。 len(x)返回int。调用上intmin会给你的错误:

'int' object is not iterable

的详细解决方案应该是象下面这样:

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

现在,看看正确的版本。

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

在这里,这个len(x) for x in s.split()部分将形成一个生成器,其中每个元素是int(单个词的长度)。并且,在发电机上调用min(),而不是在个人int上调用。所以,这工作得很好。

总之

>> min(1) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'int' object is not iterable 
>> 
>>min([1]) 
>> 1 
0

输入:你的问题是

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. 

你需要通过迭代项目min函数不是int类型

如果这里

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