“for”函数如何定义变量?

“for”函数如何定义变量?

问题描述:

我试图定义一个函数来查找句子中单词的平均长度。一切都很好,但我只是对我的函数的某些部分进行调查,即是:“for”函数如何定义变量?

random_sentence = str(input('Enter a sentence:')) 

def average(): 
    'Takes the average length of a word in a sentence inputed by user.' 
    words = random_sentence.split() 
    averageword = sum(len(word) for word in words)/len(words) 
    return averageword 

print(average()) 

averageword = sum(len(word) for word in words)/len(words) 

我明白这样做,不过,Python是怎样知道什么和和len什么是“字”是“用言语表达。“它是预定义的吗?当我将这个短语从功能中解释出来时,它会说单词没有被定义。我赞赏澄清。

for​​。

当Python执行程序时,它将文件转换为一系列标记lexical analysis。之后,令牌得到parsed以确定它们属于哪个构造。

对于您的情况,在for之前的expression token使构造成为generator expression

+0

该死的甜蜜回答+1 BLAM获得语法的一些血淋淋的细节 – 2013-02-10 18:38:22

在Y X要求y是一个迭代(即列表中,字典,字符串等)通过y和每次迭代的x定义为y [迭代#]

然后蟒迭代

所以基本上如果y = [1,2,3]

for x in y: 
    print x 

将返回

+0

这就是'for'循环! ,在示例程序中没有使用 – phihag 2013-02-10 18:38:21

+0

是的,但它是一样的东西,但写成略有不同的形式 - for关键字的处理方式与Python相同 – 2013-02-11 03:16:48

+0

for循环和生成器表达式之间存在显着差异。 for循环分配给局部变量,而生成器表达式a分配给临时(内部)一个。另外,观察'from [__future__ import print_function; for x in [1,2,3]:print(x);(print [x] for x in [1,2,3])':除非生成器表达式被消耗,它不被评估。 – phihag 2013-02-11 08:39:04

列表words是一个可迭代 - 它定义了一个__iter__方法,它返回为列表的迭代器。该for关键字列表上调用__iter__(),然后对迭代器调用next()直到StopIteration异常被抛出:

In [1]: words = ["a", "b"] 

In [2]: i = words.__iter__() 

In [3]: i 
Out[3]: <listiterator at 0x5cd82b0> 

In [4]: i.next() 
Out[4]: 'a' 

In [5]: i.next() 
Out[5]: 'b' 

In [6]: i.next() 
--------------------------------------------------------------------------- 
StopIteration        Traceback (most recent call last) 
<ipython-input-6-e590fe0d22f8> in <module>() 
----> 1 i.next() 

StopIteration: 

更多的细节有关iterables和迭代器:

http://docs.python.org/2/library/stdtypes.html#iterator-types http://getpython3.com/diveintopython3/iterators.html#a-fibonacci-iterator

“单词“是在列表解析和生成器表达式以及for循环中局部定义的。这就像一个临时变量。

认为它这种方式由“字”代“X”:

theSum = sum([len(x) for x in words]) 

(我把括号它表明,它像一个列表)。这意味着“让x是列表中的一个元素”,“对于每个x,计算它的长度并从结果中列出一个列表。“

你也可以认为它是这样的:

list = [] 
for x in words: 
    list.append(len(x)) 

theSum = sum(list) 

您可以在List Comprehensions

+0

该问题实际上不包含任何列表解析(注意括号的缺失)。那里的“for”事件属于生成器表达式,它们是列表解析的近亲。 – phihag 2013-02-10 19:25:23

+0

已注意。我把“发电机”这个词放在那里更准确。 – 2013-02-10 20:20:29

+0

对不起,但它不是[generator](http://docs.python.org/2/glossary.html#term-generator)。 – phihag 2013-02-10 20:24:01