Python 学习笔记02

1.使用in
ok=raw_input("Please enter Yes or No")
if ok in ('yes','Yes','Y')
    return true

2.函数在定义的时候可以给出参数默认值,这样使用这个函数的时候,也可以用较少的参数来调用,也可以用较多的参数来调用。
但是这个默认的值只解析一次!!!
如:   
def f(a, L=[]):
	L.append(a)
	return L
	print f(1)
	print f(2)
	print f(3)

这样会打印出
[1]
[1, 2]
[1, 2, 3]

3.函数定义的参数,可以有可变个参数,用*name,来表示一个可变参数的列表或者字典。
如 :
def cheeseshop(kind, *arguments, **keywords):

但是这个可变列表必须要在参数的后面位置。

4.Python的编码风格。
规则:
  • 使用4个空格格缩进,不要用tab
  • 折行以确保不会超过79个字符
  • 使用空格行分隔函数和类,以及函数中的大代码块
  • 可能的话,注释独占一行
  • 使用文档字符串:文档字符串的规则是:

"""Do nothing, but document it. 第一行应该是关于对象用途的简介


No, really, it doesn't do anything.如果文档字符串有多行,第二行应该空出来,与接下来的详细描述明确分隔。接下来的文档应该有一或多段描述对象的调用约定、边界效应等。
"""
  • 统一函数和类命名
  • 首选utf8 来做编码格式


5.数据结构链表常用方法:
list.append(x)

#Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
#Extend the list by appending all the items in the given list; equivalent to a[len(a):]=L

list.insert(i, x)
#在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如

a.insert(0,x) 
#会插入到整个链表之前,而a.insert(len(a), x) 相当于a.append(x) 。

list.remove(x)
#删除链表中值为x 的第一个元素。如果没有这样的元素,就会返回一个错误。


list.pop([i ])
#从链表的指定位置删除元素,并将其返回。如果没有指定索引, a.pop() 返回最后一个元素。元素随即从链表中被删除。

list.index(x)
#返回链表中第一个值为x 的元素的索引。如果没有匹配的元素就会返回一个错误。

list.count(x)
#Return the number of times x appears in the list. 返回x 在链表中出现的次数。

list.sort()
#对链表中的元素就地(原文in place,意即该操作直接修改调用它的对象——译者)进行排序。

list.reverse()
#就地倒排链表中的元素。

6.要实现队列,使用collections.deque ,它为在首尾两端快速插入和删除而设计。如下:
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

7.好用的链表内置函数,filter(),map(),reduce()
filter(function, sequence) 返回一个sequence(序列),包括了给定序列中所有调用

function(item)后返回值为true的元素。(如果可能的话, 会返回相同的类型)。
如:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

map(function, sequence) 为每一个元素依次调用function(item) 并将返回值组成一个链表返回。例如,以下程序计算立方
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

可以传入多个序列,函数也必须要有对应数量的参数,执行时会依次用各序列上对应的元素来调用函数

reduce(func, sequence) 返回一个单值,它是这样构造的:首先以序列的前两个元素调用函数function,再以返回值和第三个参数调用,依次执行下去。例如,以下程序计算1 到10 的整数之和
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55

8.两个乘号和一个数字代表指数。
x**2 就是x的平方


9.语句del 还可以从列表中删除切片或清空整个列表,del 也可以删除整个变量 如:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]

10.set(集合)


>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit # fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a j b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

11.字典,理解字典的最佳方式是把它看做无序的键:值对(key:value pairs)集合,键必须是互不相同的(在同一个字典之内)。一对大括号创建一个空的字典: fg 。初始化链表时,在大括号内放置一组逗号分隔的键:值对,这也是字典输出的方式。

字典的主要操作是依据键来存储和析取值。也可以用del 来删除键: 值对(key:value)。

如果你用一个已经存在的关键字存储值,以前为该关键字分配的值就会被遗忘。试图从一个不存在的键中取值会导致错误。字典的keys() 方法返回由所有关键字组成的链表,该链表的顺序不定(如果你需要它有序,只能调用关键字链表的sort() 方法)。可以用in 关键字检查字典中是否存在某一关键字。

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> 'guido' in tel
True

链表中存储关键字-值对元组的话,:func:dict 可以从中直接构造字典。键-值对来自某个特定模式时,可以用链表推导式简单的生成关键字-值链表。

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
{2: 4, 4: 16, 6: 36}


使用简单字符串作为关键字的话,通常用关键字参数更简单
>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

12.在字典中循环时,关键字和对应的值可以使用iteritems() 方法同时解读出来
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave

在序列中循环时,索引位置和对应值可以使用enumerate() 函数同时得到。
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe

同时循环两个或更多的序列,可以使用zip() 整体打包。
>>> 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.

需要逆向循环序列的话,先正向定位序列,然后调用reversed() 函数
>>> for i in reversed(xrange(1,10,2)):
... print i
...
9
7
5
3
1

要按排序后的顺序循环序列的话,使用sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列。


16. Looping Techniques 循环技巧51
Python Tutorial, Release 2.7
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值