—————————————————————————————————————————
>>> x, y, z = 1, 3, 5 //序列解包 ———— 将多个值的序列解开 让后放到变量的序列中
>>> print x, y, z
1 3 5
>>> x, y = y, x
>>> print x, y, z
3 1 5
—————————————————————————————————————————
>>> d = {'apple': 12, 'orange': 5, 'watermelon': 2}
>>> key, value = d.popitem()
>>> key
'orange'
>>> value
5
>>> d
{'watermelon': 2, 'apple': 12}
—————————————————————————————————————————
>>> s = 'water' //增量赋值
>>> s += 'melon'
>>> s
'watermelon'
>>> s *= 2
>>> s
'watermelonwatermelon'
—————————————————————————————————————————
解释器视: False None 0 ‘’ () [] {} 为假 其他为真
>>> True == 1
True
>>> False == 0
True
>>> bool('')
False
>>> bool(2)
True
—————————————————————————————————————————
n = raw_input('name: ')
if n.endswith('Gumby'):
if n.startswith('Mr. ')
print 'hello, Mr. Gumby'
elif n.startswith('Mrs. '):
print 'hello, Mrs. Gumby'
else:
print 'hello, Gumby'
else:
print 'hello, stranger'
—————————————————————————————————————————
>>> x = [1, 2, 3]
>>> y = [2, 4]
>>> x is not y
True
>>> del x[2]
>>> x
[1, 2]
>>> y[1] = 1
>>> y
[2, 1]
>>> y.reverse()
>>> y
[1, 2]
>>> x == y
True
>>> x is y //is运算判断的是同一性 而不是相等性
False
—————————————————————————————————————————
>>> chr(97)
'a'
>>> ord('b')
98
—————————————————————————————————————————
>>> n = raw_input('name: ') or '<unknown>' //如果raw_input语句返回值为真(不是空字符串) 那其值就赋给n 否则将默认对'<unknown>'赋值给n
name:
>>> n
'<unknown>'
—————————————————————————————————————————
>>> age = 24
>>> assert 0 < age < 18, 'It is adult' //置入检查点 确保程序中某条件一定为真才能让程序正常的工作
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: It is adult
—————————————————————————————————————————
name = ''
while not name or name.isspace() //条件为真时重复执行代码 也可用while not name.strip()
name = raw_input('Please enter your name: ')
print 'Hello, %s!' % name
—————————————————————————————————————————
>>> words = ['this', 'is', 'a', 'book']
>>> for w in words: print w
...
this
is
a
book
>>> for n in range(1, 5): print n //range函数包含下限 但不包含上限 若希望下限为0 可只给出上限
...
1
2
3
4
—————————————————————————————————————————
>>> d = {'x': 2, 'y': 4, 'z': 8}
>>> for key, value in d.items(): print key, 'corresponds to', value
...
y corresponds to 4 //迭代时 字典中的键和值都能保证被处理 但是处理的顺序不确定
x corresponds to 2
z corresponds to 8
—————————————————————————————————————————
>>> names = ['damon', 'george', 'anne', 'beth'] //并行迭代
>>> ages = [23, 11, 54, 36]
>>> for i in range(len(names)): print names[i], 'is', ages[i], 'years old'
...
damon is 23 years old
george is 11 years old
anne is 54 years old
beth is 36 years old
—————————————————————————————————————————
>>> names = ['damon', 'george', 'anne', 'beth']
>>> ages = [45, 61, 14, 26]
>>> zip(names, ages)
[('damon', 45), ('george', 61), ('anne', 14), ('beth', 26)]
>>> for name, age in zip(names, ages): print name, 'is', age, 'years old' //循环中解包元组
...
damon is 45 years old
george is 61 years old
anne is 14 years old
beth is 26 years old
—————————————————————————————————————————
>>> zip(range(4), xrange(200000)) //处理不等长的序列 xrange不推荐用range替换 因为range会计算所有的数字 花费很长时间
[(0, 0), (1, 1), (2, 2), (3, 3)]
—————————————————————————————————————————
>>> list(reversed('apple')) //reverse和sort方法是针对列表的 而不是字符串 reversed方法返回的是一个迭代对象
['e', 'l', 'p', 'p', 'a']
>>> ''.join(reversed('apple'))
'elppa'
—————————————————————————————————————————
from math import sort //寻找100以内最大平方数
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print n
break
—————————————————————————————————————————
while True:
w = raw_input('enter a word: ')
if not word: break //不输入单词则循环结束
print 'The word was ' + w
—————————————————————————————————————————
>>> [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)]
result = []
for x in range(3):
for y in range(3):
result.append((x, y))
—————————————————————————————————————————
>>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> letterGirls = {}
>>> for girl in girls: letterGirls.setdefault(girl[0], []).append(girl)
...
>>> letterGirls
{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}
>>> print [b+'+'+g for b in boys for g in letterGirls[b[0]]] //b[0]得到的是男孩名字的首字母 以此为字典letterGirls的引索 得到首字母相同的女孩的名字
['chris+clarice', 'arnold+alice', 'bob+bernice'] //字符串相加
—————————————————————————————————————————
>>> x = ['hello', 'world']
>>> y = x
>>> y[1] = 'python'
>>> x //x和y指向同一个列表
['hello', 'python']
>>> del x //删除的是变量 而不是值
>>> y
['hello', 'python']
—————————————————————————————————————————
>>> from math import sqrt
>>> scope = {} //空间命名 ———— 作用域
>>> exec 'sqrt = 1' in scope
>>> sqrt(9) //潜在的破坏性代码并不会覆盖sqrt函数 通过exec赋值的变量sqrt只在它的作用域内有效
3.0
>>> scope['sqrt']
1
>>> len(scope)
2
>>> scope.keys()
['__builtins__', 'sqrt']
—————————————————————————————————————————
>>> scope = {}
>>> len(scope)
0
>>> scope['x'] = 2
>>> scope['y'] = 4
>>> eval('x * y', scope)
8
>>> len(scope)
3
>>> scope.keys()
['y', 'x', '__builtins__']
>>> scope = {}
>>> exec 'x = 2' in scope //用与执行python程序相同的方式来执行字符串
>>> eval ('x * x', scope) //对写在字符串中的表达式进行计算并且返回结果
4
—————————————————————————————————————————
>>> def fibs(n): //创建函数
... result = [0, 1]
... for i in range(n - 2):
... result.append(result[-2] + result[-1])
... return result //return语句用来从函数中返回值 并跳出函数 return后可不跟任何值 此时返回None
...
>>> callable(fibs) //判断函数是否可调用
True
>>> fibs(10) //当函数内部把传递进来的参数重绑定后 函数外对应的变量不会受到影响
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
—————————————————————————————————————————
>>> def change(n):
... n[0] = 'Mr.Gumby'
...
>>> names = ['Mrs.Entity', 'Mrs.Thing']
>>> change(names)
>>> names
['Mr.Gumby', 'Mrs.Thing']
>>> names = ['Mrs.Entity', 'Mrs.Thing']
>>> change(names[:])
>>> names
['Mrs.Entity', 'Mrs.Thing']
—————————————————————————————————————————
>>> storage = {}
>>> storage['first'] = {}
>>> storage['middle'] = {}
>>> storage['last'] = {}
>>> storage
{'middle': {}, 'last': {}, 'first': {}}
>>> me = 'Magnus Lie Hetland'
>>> storage['first']['Magnus'] = [me]
>>> storage['middle']['Lie'] = [me]
>>> storage['last']['Hetland'] = [me]
>>> storage
{ 'middle': {'Lie': ['Magnus Lie Hetland']},
'last': {'Hetland': ['Magnus Lie Hetland']},
'first': {'Magnus': ['Magnus Lie Hetland']}
}
>>> storage['middle']['Lie']
['Magnus Lie Hetland']
>>> my_sister = 'Anne Lie Hetland'
>>> storage['first'].setdefault('Anne', []).append(my_sister)
>>> storage
{ 'middle': {'Lie': ['Magnus Lie Hetland']},
'last': {'Hetland': ['Magnus Lie Hetland']},
'first': {'Anne': ['Anne Lie Hetland'],
'Magnus': ['Magnus Lie Hetland']
}
}
>>> storage['middle'].setdefault('Lie', []).append(my_sister)
>>> storage
{ 'middle': {'Lie': ['Magnus Lie Hetland', 'Anne Lie Hetland']},
'last': {'Hetland': ['Magnus Lie Hetland']},
'first': {'Anne': ['Anne Lie Hetland'],
'Magnus': ['Magnus Lie Hetland']
}
}
—————————————————————————————————————————
>>> def init(data):
... data['first'] = {}
... data['middle'] = {}
... data['last'] = {}
>>> storage = {}
>>> init(storage)
>>> storage
{'middle': {}, 'last': {}, 'first': {}}
>>> def lookup(data, label, name): //name为'first' 'middle'或'last'
... return data[label].get(name) //未找到时 默认的返回值为None
>>> def store(data, full_name):
... names = full_name.split() //通过拆分full_name 得到一个叫做names的列表['first', 'middle', 'last']
... if len(names) == 2: names.insert(1, '') //如果names长度为2 则插入一个空字符串作为中间名middle
... labels = 'first', 'middle', 'last' //将三个字符串作为元组储存在labels中
... for label, name in zip(labels, names):
... people = lookup(data, label, name)
... if people: //如果查找到 则将新名字full_name添加到原来具有相同标签的名字列表的尾部
... people.append(full_name)
... else: //否则 将其插入到新的对应列表中
... data[label][name] = [full_name]
>>> MyName = {}
>>> init(MyName)
>>> store(MyName, 'Magnus Lie Hetland')
>>> lookup(MyName, 'middle', 'Lie')
['Magnus Lie Hetland']
>>> store(MyName, 'Robin Hood')
>>> store(MyName, 'Robin Locksley')
>>> lookup(MyName, 'first', 'Robin')
['Robin Hood', 'Robin Locksley']
>>> store(MyName, 'Mr. Gumby')
>>> lookup(MyName, 'middle', '')
['Robin Hood', 'Robin Locksley', 'Mr. Gumby']
—————————————————————————————————————————
>>> def hello(name = 'stranger', greeting = 'hello', punctuation = '!'):
... print '%s, %s%s' % (greeting, name, punctuation)
>>> hello()
hello, stranger!
>>> hello('Gumby')
hello, Gumby!
>>> hello('Gumby', 'hi', '@#')
hi, Gumby@#
—————————————————————————————————————————
>>> def print_params(x, y, z = 3, *pospar, **keypar):
... print x, y, z
... print pospar //收集其余的位置参数 元组
... print keypar //收集关键字参数 字典
...
>>> print_params(1, 2, 4, 5, 6, 7, a = 2, b = 6)
1 2 4
(5, 6, 7)
{'a': 2, 'b': 6}
>>> print_params(1, 2)
1 2 3
()
{}
—————————————————————————————————————————
>>> def store(data, *full_names):
... for full_name in full_names: //实现多个名字同时储存
... names = full_name.split()
... if len(names) == 2: names.insert(1, '')
... labels = 'first', 'middle', 'last'
... for label, name in zip(labels, names):
... people = lookup(data, label, name)
... if people:
... people.append(full_name)
... else:
... data[label][name] = [full_name]
...
>>> d = {}
>>> init(d)
>>> store(d, 'Han Solo')
>>> store(d, 'Luke Skywalker', 'Anakin Skywalker')
>>> lookup(d, 'last', 'Skywalker')
['Luke Skywalker', 'Anakin Skywalker']
—————————————————————————————————————————
>>> def with_star(**data): //允许使用不定数目的参数
... print data['name'], 'is', data['age'], 'years old'
...
>>> args = {'name': 'Mr. Gumby', 'age': 28}
>>> with_star(**args) //分割字典或是序列
Mr. Gumby is 28 years old
—————————————————————————————————————————
>>> def power(x, y, *others):
... if others:
... print 'others: ', others
... return pow(x, y)
...
>>> p = (5,)*2
>>> power(*p)
3125
>>> p = (5,)*4
>>> power(*p)
others: (5, 5)
3125
—————————————————————————————————————————
>>> x = 1
>>> scope = vars() //赋值后 x引用到值1 类似于一个字典 vars函数可以返回这个"不可见的"字典(命名空间或作用域)
>>> scope['x']
1
>>> scope['x'] += 1
>>> x
2
—————————————————————————————————————————
除全局作用域外 每个函数调用都会创建一个新的作用域(局部命名空间) 这个新的作用域作用于函数内的代码 不对外部产生影响
在函数内部声明全局变量 global x
在函数内部获取与局部变量或参数名字相同的全局变量 globals()['parameter']
—————————————————————————————————————————
def factorial(n): //阶乘
... result = n
... for i in range(1, n):
... result *= i
... return result
...
>>> factorial(4)
24
>>> def factorial(n): //递归实现
... if n == 1:
... return 1
... else:
... return n * factorial(n-1)
...
>>> factorial(5)
120
—————————————————————————————————————————
>>> def power(x, n): //(整数)幂运算
... result = 1
... for i in range(n):
... result *= x
... return result
...
>>> power(3, 4)
81
>>> def power(x, n): //递归实现
... if n == 0:
... return 1
... else:
... return x * power(x, n-1)
...
>>> power(4, 3)
64
—————————————————————————————————————————
>>> map(str, range(5)) //[str(i) for i in range(5)] map函数可将序列中的元素全部传递给一个函数
['0', '1', '2', '3', '4']
—————————————————————————————————————————
>>> def func(x):
... return x.isalnum() //判断字符变量x是否只含有字母或数字
...
>>> func('app')
True
>>> seq = ['9*2', 'x80', 'ban!', '36']
>>> filter(func, seq) //返回其函数为真的元素的列表
['x80', '36']
—————————————————————————————————————————