python3里面的range()函数

来源:互联网 发布:什么是淘宝直通车? 编辑:程序博客网 时间:2024/05/22 04:45

①python3中的range函数

奇怪的现象

在paython3中

print(range(10))
得出的结果是 range(0,10) ,而不是[0,1,2,3,4,5,6,7,8,9] ,为什么呢?

官网原话:

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:

翻译:

可以看到上面这个很奇怪,在很多种情况下,range()函数返回的对象的行为都很像一个列表,但是它确实不是一个列表,它只是在迭代的情况下返回指定索引的值,但是它并不会在内存中真正产生一个列表对象,这样也是为了节约内存空间。

我们称这种对象是可迭代的,或者是可迭代对象,还有一种对象叫迭代器,它们需要从一个可迭代对象中连续获取指定索引的值,一直到索引结束。list()函数就是这样一个迭代器,它可以把range()函数返回的对象变成一个列表。

总结:

range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。

list() 函数是对象迭代器,把对象转为一个列表。返回的变量类型为列表。

②在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里
用的话要 先引入
from functools import reduce

③PIL(Python Imaging Library)是Python一个强大方便的图像处理库,名气也比较大。不过只支持到Python 2.7。

PIL官方网站:http://www.pythonware.com/products/pil/
Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库。目前最新版本是3.0.0。

Pillow的Github主页:https://github.com/python-pillow/Pillow
Pillow的文档(对应版本v3.0.0):https://pillow.readthedocs.org/en/latest/handbook/index.html
Pillow的文档中文翻译(对应版本v2.4.0):http://pillow-cn.readthedocs.org/en/latest/
Python 3.x 安装Pillow
给Python安装Pillow非常简单,使用pip或easy_install只要一行代码即可。

在命令行使用PIP安装:

pip install Pillow
或在命令行使用easy_install安装:

easy_install Pillow
安装完成后,使用from PIL import Image就引用使用库了。比如:

from PIL import Image
im = Image.open(“bride.jpg”)
im.rotate(45).show()
简单,方便。
https://www.ywlib.com/archives/37.html

原创粉丝点击