python学习笔记

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值