note on python

iterator

Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method __next__() which accesses elements in the container one at a time. When there are no more elements, __next__() raises a StopIteration exception which tells the for loop to terminate.You can call the __next__() method using the next() built-in function

可以自己实现一个类的for loop:

class A:
	class it:
		def __init__(s,a):
			s.a=a
			s.l=len(s.a.l)+len(s.a.l2)
			s.i=0
		def __next__(s):
			if s.i==s.l:
				raise StopIteration
			a=0
			if s.i<len(s.a.l):
				a= s.a.l[s.i]
			else:
				a= s.a.l2[s.i-len(s.a.l)]
			s.i=s.i+1
			return a
	def __init__(s):
		s.l=[1,2,4,5]
		s.l2=[4,3,2,0]
	def __iter__(s):
		return A.it(s)

>>> a=A()
>>> [i for i in a]
[1, 2, 4, 5, 4, 3, 2, 0]

generator

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed).

def gen(a):
	for i in a.l:
		yield i
	for i in a.l2:
		yield i

>>>for i in gen(a):
	print (i,end=‘,‘)

1,2,4,5,4,3,2,0,

generator expression

def gen():
	return ((i,j)for i in range(10)for j in range(9))
或:
for a in((i,j)for i in range(10)for j in range(9)):
	print (a)

for a in (...generator exp...)是在每次call next()时才生成a,而for a in [...list comprehension...]是提前就生成一个列表,据说前者效率更高

class and instance variables

我的理解,对于mutable变量,对象复制类的变量的一个“指针“:

>>> class A:
	li=[]
	def add(s,x):
		s.li.append(x)

>>> a=A()
>>> a.add(3)
>>> a.li
[3]
>>> b=A()
>>> b.add(4)
>>> b.li#b.li像是A.li的一个引用,已经被a.li修改过
[3, 4]

正确的做法:

>>> class A:
	def __init__(s):
		s.li=[]#每次创建对象都生成一个对象自己的列表
	def add(s,x):
		s.li.append(x)

>>> a=A()
>>> a.add(3)
>>> a.li
[3]
>>> b=A()
>>> b.add(4)
>>> b.li
[4]

而对于immutable 变量则类似于按值传递(尽管python中没有这些概念),不会有这个问题

时间: 2024-11-10 11:35:26

note on python的相关文章

Note of Python Math

Note of Python Math math 库是Python 提供的内置数学类函数库,而其中复数类型常用于科学计算,一般计算并不常用,因此math 库不支持复数类型.math 库一共提供4个数学常数和44个函数(包括16个数值表示函数.8个幂对数函数.16个三角对数函数和4个高等特殊函数). 1. 调用库函数 (1) 导入库函数:import  <库名> 使用库中函数:<库名> . <函数名> (<函数参数>) (2) 导入库函数:from  <

使用gdb调试Python进程

http://www.cnblogs.com/dkblog/category/287362.html https://wiki.python.org/moin/DebuggingWithGdb There are types of bugs that are difficult to debug from within Python: segfaults (not uncaught Python exceptions) hung processes (in cases where you can

[学习笔记] Python标准库简明教程 [转]

1 操作系统接口 os 模块提供了一系列与系统交互的模块: >>> os.getcwd() # Return the current working directory '/home/minix/Documents/Note/Programming/python/lib1' >>> os.chdir('~/python') # Change current working directory Traceback (most recent call last): File

Python模块搜索及模块安装

[import模块] 和C中的#include不同,Python中的import语句并不是简单的把一个文件插入另外一个文件. 导入其实是运行时的运算,程序第一次导入指定文件时,会执行以下步骤, 1. 找到模块文件 2. 编译成位码 3. 执行模块中的代码来创建所定义的模块 并生成.pyc字节码文件,这三个步骤只在程序执行时,模块第一次导入时会进行.之后导入相同的模块时,会跳过这三个步骤,而只提取内存中已加载的模块对象,速度要快的多. NOTE: 1. Python把已加载的模块放在内置的sys.

【翻译】Python标准模块库之-------Subprocess

原文来自官网文档:https://docs.python.org/2.7/ 17.1. subprocess — Subprocess management New in version 2.4. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends

Python/C++ in Visual Studio: An Alternative to Matlab/MEX

来自Andrew Delong的博客 http://andrewdelong.wordpress.com/2012/11/03/pythonc-in-visual-studio-an-alternative-to-matlabmex/ I spent much of my PhD working in Matlab with C++ MEX extensions. Debugging MEX extensions is frustrating: either you resort to prin

(转)详解Python闭包

Closures In Python Entirely copied from here All I want is to mark it, thanks for this nice article. You might have lived a long and happy coding life without ever needing to know what closures are. For one, many languages like C or C++ don't even su

Python字符串操作精彩汇集

字符串的格式化 Note: 基于 Python 3.6 基本形式: # 注意 如果要格式化多个值,元组中元素的顺序必须和格式化字符串中替代符的顺序一致 # 否则,可能出现类型不匹配的问题.如果将上例中的%s和%d调换位置,将抛出如下异常: # TypeError: int argument required "%s" % str1 "%s %s" % (str1, str2) 原文地址:https://www.cnblogs.com/suesun/p/9882392

python国际化 i18n 和中英文切换

Python通过gettext模块支持国际化(i18n),可以实现程序的多语言界面的支持,下面是我的多语言支持实现: 1.         在python安装目录下的./Tools/i18n/(windows下例 D:\Program Files\Python25\Tools\i18n)目录中找到pygettext.py运行之,生成翻译文件模版messages.pot,内容大概是这个样子: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANI