In [1]:
#number = range(10)
size = 10
even_numbers = []
n = 0
while n < size:
if n % 2==0:
even_numbers.append(n)
n += 1
print even_numbers
我们做的事情在数学定义上看来像是什么呢?
$\{x|x \in \{0,1,2,....,9\}, s.t. x\%2==0 \}$
In [1]:
{ x for x in range(10) if x % 2==0 }
Out[1]:
这种代码形式称为Comprehensions,也就是解析(推导式)。
形式: {expr(item) for item in iterable if cond_expr(item)} 或者中括号、小括号包裹
In [2]:
print [ x**2 for x in xrange(10)]
回忆enumerate
任务:把一个list里的元素和索引号找出来,更新回原来的list中去
循环操作可变类型
In [2]:
Lord_of_ring = ['Ainur','Dragons','Dwarves','Elves','Ents','Hobbits','Men','Orcs']
print type(enumerate(Lord_of_ring)),enumerate(Lord_of_ring)
for idx,element in enumerate(Lord_of_ring):
Lord_of_ring[idx] ="{0}:{1}".format(idx,element)
print Lord_of_ring
List Comprehension构造新列表
In [7]:
test =['Ainur','Dragons','Dwarves','Elves','Ents','Hobbits','Men','Orcs']
def _trans(idx,element):
return '{0}:{1}'.format(idx,element)
print [_trans(idx,element) for idx,element in enumerate(test)]
print ['{0}:{1}'.format(idx,element) for idx,element in enumerate(test) ]
老朋友Iterable,isinstance()检查
In [8]:
import collections
print isinstance("Hello,world", collections.Iterable)
print isinstance( test, collections.Iterable)
字典也是Iterable:
In [9]:
language={"Scala":"Martin Odersky",\
"Clojure":"Richy Hickey",\
"C":"Dennis Ritchie",\
"Standard ML":"Robin Milner"}
['{0:<12} created by {1:<15}'.format(la,ua)\
for la,ua in language.iteritems()]
Out[9]:
多重解析
In [3]:
print [(x+1,y+1) for x in xrange(4) for y in xrange(4)]
print [(x+1,y+1) for x in xrange(4) for y in xrange(4) if y<x]
print [(x+1,y+1) for x in xrange(4) for y in xrange(x)]
使用小括号做Comprehension返回生成器对象,占用O(1)内存空间:
In [11]:
num=range(0,20)
simple_generator=(x**2 for x in num if x > 0)
print simple_generator
for element in simple_generator:
print element,
使用小括号解析并不会返回一个不可变元组而是生成器,是一个需要强记的规则;然而大括号解析式就普通了许多。
In [4]:
x = range(10)
print { i for i in x if i%2==0 }
print { idx:i**2 for idx,i in enumerate(x) if i%2==0 }
注意生成字典时使用key:value的形式就可以了。
In [13]:
war3_char = ['Orc','Humans','Undead','Night Elves']
dota_hero = ['Blade Master','Archmage','Death King','Demon Hunter']
Your_choice=zip(war3_char,dota_hero)
print Your_choice
取回原来的列表:
In [14]:
choice1,choice2,choice3,choice4 = Your_choice
print zip(choice1,choice2,choice3,choice4)
用*把Your_choice的内容而不是它本身作为参数传递
In [13]:
print zip(*Your_choice)
* 告诉Python即将传入的参数Your_choice不是单独一个序列,而是把Your_choice中的每一项作为参数
从下面的字典里按值来排序,取到值最大或者值最小的那条记录:
In [3]:
Base_Damage={'Blade Master':48,'Death King':65,'Tauren Chieftain':51}
print zip(Base_Damage.itervalues(),Base_Damage.iterkeys())
max_Damage=max(zip(Base_Damage.itervalues(),Base_Damage.iterkeys()))
min_Damage=min(zip(Base_Damage.itervalues(),Base_Damage.iterkeys()))
print max_Damage,min_Damage
花样传参
刚才已经知道能把列表加星号保持有序地作为一个个参数(argument)传给方法/函数:
In [5]:
def triplesum(a,b,c):
return a*100+b*10+c
print triplesum(*[1,2,3])
print triplesum(1,2,3)
带默认值的参数叫keyword arguments(kargs):
In [12]:
def triplesum_default(a=0,b=0,c=0,*args):
return a*100+b*10+c
def ntuplesum_default(*args):
sum = 0
for i in args:
sum*=10
sum+=i
return sum
print triplesum_default(*[1,2,3,4])
print ntuplesum_default(*[1,2,3,5])
print ntuplesum_default(1,2,3,5,6,7,8)
print triplesum_default(*[1,3])
print triplesum_default(**{'b':2,'c':3,'a':1})
print triplesum_default(**{'c':3,'a':1})
深浅拷贝:关系到变量的正确修改与复制
变量的属性:
In [6]:
import copy
unit = ['name',['Base_Damage',65.00]]
my_hero = unit[:] #使用切片拷贝
your_hero = list(unit) #使用工厂方法拷贝
its_hero = copy.copy(unit) #使用浅拷贝
print [id(x) for x in unit,my_hero,your_hero,its_hero]
print [id(x[0]) for x in unit,my_hero,your_hero,its_hero]
print [id(x[1]) for x in unit,my_hero,your_hero,its_hero]
假设一下,你的英雄打到了豪华套装(your_hero),或者游戏中的英雄(my_hero)有了一个嗜血的加成效果,所以数值会出现一些不一样的地方。
In [7]:
my_hero[0] = 'Kel\'Thuzad'
your_hero[0] = 'Mirana'
its_hero[0] = 'Morphling'
print my_hero,your_hero,its_hero
my_hero[1][1]=100.00 # 先更改一个对象的值
print my_hero,your_hero,its_hero # 可以看出值的情况不对,my_hero
为什么相互影响了呢?
In [8]:
print [id(x[0]) for x in unit,my_hero,your_hero,its_hero]
print [id(x[1]) for x in unit,my_hero,your_hero,its_hero]
In [9]:
import copy
unit = ['name',['Base_Damage',[65.00]]]
my_hero = copy.deepcopy(unit)
your_hero = copy.deepcopy(unit)
my_hero[0] = 'Kel\'Thuzad'
your_hero[0] = 'Mirana'
my_hero[1][1][0] = 100.00
print my_hero,your_hero
In [10]:
print [id(x) for x in my_hero]
print [id(x) for x in your_hero]
会犯错的是人,能原谅人的是……
Python允许程序在运行当中检测错误。
每检测到一个错误,Python解释器就引发一个异常并报出详细的错误信息:
In [11]:
y = 6
x = 5
x,y = y,x
1/0
如果你需要添加错误检测和异常处理,需要把你想要书写的代码组封装在try-except语句中。
In [13]:
try:
x = 1/0
y = range(10)[10]
except Exception:
print "Wow, such cute error"
常见的python中的异常,举例来说:
In [14]:
try:
x = 1/0
y = range(10)[10]
except ZeroDivisionError,e1:
print "Wow, such cute divisor"
except IndexError,e2:
print "Wow, such cute index"
print e1
In [15]:
try:
x = 1/2
y = range(10)[10]
except ZeroDivisionError,e1:
print "Wow, such cute divisor"
except IndexError,e2:
print "Wow, such cute index"
print e2
通过try-except-else-finally来感受异常处理的完全体吧!
并用另一种方式记录异常。
In [22]:
import sys
try:
x = 1/0
y = range(10)[-1]
except Exception,error:
x = 0
y = 9
print 'X,Y is corrected.'
info = sys.exc_info()
else:
print 'Catch no exceptions. Great!'
finally:
z = x + y
print z**2 + x**2 + y**2
print 'Finished'
print '\n',error,'\n',info[0],'\n',info[1],'\n',info[2],info[2].tb_lineno
In [ ]: