import的格式:
import
somemodule
from
somemodule import somefunction
from
somemodule import somefunction, anotherfunction, yetanotherfunction
from
somemodule import *
import
math as foobar
§5.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
name
= raw_input('What is your name? ')
if
name.endswith('Gumby'):
if
name.startswith('Mr.'):
print
'Hello, Mr. Gumby'
elif
name.startswith('Mrs.'):
print
'Hello, Mrs. Gumby'
else:
print
'Hello, Gumby'
else:
print
'Hello, stranger'
比较操作:
x
== y x equals y.
x
x > y x is greater than y.
x >= y x is greater than or equal to y.
x
x != y x is not equal to y.
x is y x and y are the same object.
x is not y x and y are different objects.
x in y x is a member of the container
(e.g., sequence) y.
x not in y x is not a member of the
container (e.g., sequence) y.
COMPARING INCOMPATIBLE
比较也可以嵌套:0
>>>
x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False
不要在基本的,不可改变的类型,比如numbers and strings中使用is,这些类型在python内部处理。
三元运算:a if b else c
断言:
>>>
age = -1
>>> assert 0
Traceback (most recent call last):
File "", line 1, in
?
AssertionError: The age must be realistic
§5.5 循环
name = ''
while not name:
name = raw_input('Please enter your name:
')
print 'Hello, %s!' % name
for number in range(1,101):
print number
xrange一次只产生一个数,在大量循环的时候可以提高效率,一般情况没有明显效果。
与字典配合使用:
d
= {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]
不过排序的为您提要自己处理。
names
= ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print names, 'is', ages, 'years old'
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
from math import sqrt
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print n
break
from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"
可见for语句也可以有else。
§5.6 List Comprehension
[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)]
>>> girls = ['alice', 'bernice',
'clarice']
>>> boys = ['chris', 'arnold',
'bob']
>>> [b+'+'+g for b in boys for g
in girls if b[0] == g[0]]
['chris+clarice', 'arnold+alice', 'bob+bernice']
这里类似数据库里面的连接。一种更有效的方法:
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]]]
§5.7 pass, del, 和
exec
pass:什么都不做
del:删除变量
>>> from math import sqrt
>>> scope = {}
>>> exec 'sqrt = 1' in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1