python学习笔记5

1.print和import
python 3.0中,print不再是语句,而是函数

使用逗号输出
>>> 1,2,3
(1, 2, 3)
>>> print 1,2,3
1 2 3
>>> print(1,2,3)
(1, 2, 3)

>>> name = 'test'
>>> print 'name:',name
name: test
>>> print 'name:',',',name
name: , test
>>> print 'name:'+',',name
name:, test

import
import somemodule
from somemodule import somefunction
from somemodule import somefunction,anotherfunction
from somemodule import *

>>> import math as t
>>> t.sqrt(4)
2.0

2.赋值魔法

序列解包
>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>> x,y = y,x
>>> print x,y,z
2 1 3
>>> values = 1,2,3
>>> values
(1, 2, 3)
>>> x,y,z = values
>>> x
1

应用
>>> person = {'name':'test','friend':'test2'}
>>> key,value = person.popitem()
>>> key
'name'
>>> key,value = person.popitem()
>>> key
'friend'
>>> key,value = person.popitem()

Traceback (most recent call last):
File " <pyshell#39>", line 1, in 
key,value = person.popitem()
KeyError: 'popitem(): dictionary is empty'

所解包中的序列中的元素数量必须和放置在赋值符号=左边的变量数量完全一致,否则python会在赋值时报错
>>> x,y,z = 1,2

Traceback (most recent call last):
File " <pyshell#40>", line 1, in 
x,y,z = 1,2
ValueError: need more than 2 values to unpack

python3.0中有另外一个解包的特性,例如
a,b,rest* = [1,2,3,4],最终会在a和b都被赋值后将其他的参数都收集到rest中

3.条件和条件语句

下面的值在作为布尔表达式的时候,会被解释器看作假(false):
false none 0 "" () [] {}
其他一切都被解释为真
事实上,True和False只不过是1和0的一种华丽的说法而已---看起来不同,但作用不同

>>> bool('abc')
True
>>> bool(12)
True
>>> bool('')
False
>>> bool(0)
False

条件执行和if语句

[python]
name = raw_input('what is your name?')
if name.endswith('test'):
    if name.startswith('Mr.'):
        print 'hello,Mr.test'
    elif name.startswith('Mrs.'):
        print 'hello,Mrs.test'
else:
    print 'no'
[/python]
相等运算符
>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False

==运算符判定两个对象是否相等,使用is判定是否等同(同一个对象)

字符串和序列比较
>>> "alpha" < "aeta"
False
>>> "alpha" < "xeta"
True
>>> [1,2] < [2,1]
True
>>> [2,[1,4]] < [2,[1,5]]
True
>>> 'Fade'.lower() == 'faDE'.lower()
True

while循环

[php]
name = ''
while not name:
    name = raw_input('what is your name?')
print 'hello %s!' % name   

name = ''
while not name or name.isspace():
    name = raw_input('what is your name?')
print 'hello %s!' % name   

name = ''
while not name.strip():
    name = raw_input('what is your name?')
print 'hello %s!' % name
[/php]
for循环
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[python]
for number in range(0,10):
    print number
[/python]
如果能使用for,尽量不要用while
xrange类似range,区别range一次创建整个序列,而xrange一次只创建一个数
当迭代一个巨大的数时,xrange更高效
在python3.0中range会被转换成xrange风格

一些迭代工具
并行迭代
>>> names = ['a','b','c']
>>> ages = [12,14,16]
>>> zip(names,ages)
[('a', 12), ('b', 14), ('c', 16)]

[python]
names = ['a','b','c']
ages = [12,14,16]

for i in range(len(names)):
    print names[i],'age is',ages[i]

for name,age in zip(names,ages):
    print name,'age is',age

#output
a age is 12
b age is 14
c age is 16
[/python]
zip可以应付不等长的序列,最短的序列用完的时候就会停止
>>> zip(range(5),range(10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> zip(range(5),xrange(10))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
上面的代码,不推荐使用range替换xrange,range会计算所有的数字,这要花费很长时间

编号迭代

[python]
strings = ['a','b','c']
for index,string in enumerate(strings):
    if 'b' in string:
        strings[index] = 'd'
print strings
#output
['a', 'd', 'c']
[/python]
翻转和排序迭代
>>> sorted([4,2,5])
[2, 4, 5]
>>> sorted(4,2,5)

Traceback (most recent call last):
File " <pyshell#37>", line 1, in 
sorted(4,2,5)
TypeError: 'int' object is not iterable
>>> sorted('hello world!')
[' ', '!', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> reversed('hello world!')

>>> list(reversed('hello world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']
>>> ' '.join(reversed('hello world!'))
'! d l r o w o l l e h'

4.列表推导式---轻量级循环
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]

>>> [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> [(x,y) for x in range(3) for y in range(3) if x == 1]
[(1, 0), (1, 1), (1, 2)]

[python]
#男、女名字首字母相同
girls = ['alice','bernice','clarice']
boys = ['chris','arnold','bob']
letterGirls = {}
for girl in girls:
    letterGirls.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]

#output
['chris+clarice', 'arnold+alice', 'bob+bernice']
[/python]
pass、del、exec

[python]
if name == 'a':
    print 'a'
elif name == 'b':
    #什么都不做
    pass
elif name == 'c':
    print 'c'
[/python]
>>> x = ['hello','world']
>>> y = x
>>> y[1] = 'python'
>>> x
['hello', 'python']
>>> del x
>>> x

Traceback (most recent call last):
File " <pyshell#58>", line 1, in 
x
NameError: name 'x' is not defined
>>> y
['hello', 'python']
x和y都指向同一个列表,但是删除x不会影响y,原因是删除只是名称,不是列表本身
事实上,python是没有办法删除值的

使用exec和eval执行和求值字符串
>>> exec "print 'hello,world!'"
hello,world!

eval用于求值,类似于exec,它会执行一系列python语句,而eval会计算python表达式,并且返回结果值
>>> eval(raw_input('Enter:'))
Enter:1+2
3



你可能感兴趣的:(python,python学习笔记)