1.打包
def write_multiple_items(file, separator, *args, **args2):
print args
print args2
write_multiple_items('a','b','c','d',name='andy', age=20, gender='man')
2.拆包
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
>>> def parrot(voltage, state='a stiff', action='voom'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it.",
... print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
3.Lambda表达式
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
4.遍历列表时候同时打印键值对
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
-----------
遍历字典同时打印键值对
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
5.把两个列表按对组成字典(一个列表中的值做key,另一个列表中的值做value)遍历:
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print 'What is your {0}? It is {1}.'.format(q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
6.列表倒序排列:
>>> for i in reversed(xrange(1,10,2)):
... print i
...
9
7
5
3
1
7.对列表排序后输出(原列表顺序不变):
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)): //set可以把basket里面的元素去重
... print f
...
apple
banana
orange
pear
8. while 和 if 条件语句,可以包括比较运算符和操作数。
比较运算符:in, not in, is, not is
比较运算可以连着写,比如: a < b == c 等价于 (a<b) and (b==c)
A and not B or C
等价于 (A and (not B)) or C