`

python笔记1

阅读更多

1、列表和元组

列表和元组之间的主要差别是一种易变性:可以更改、添加或删除列表中的项,但是不能更改元组,除了这个特点之外,读者还会发现他们所应用的位置存在概念上的差别。可以把列表当作数组使用,以保留文件中的多行文本。
列表适用于以同一中方式处理的很多个项,而元组通常表示一个项的不同

创建列表

>>> list((5,10))
[5, 10]
>>> list("the world")
['t', 'h', 'e', ' ', 'w', 'o', 'r', 'l', 'd']
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(2,20,3)
[2, 5, 8, 11, 14, 17]
>>> range(2,20,-3)
[]
>>> range(20,2,-3)
[20, 17, 14, 11, 8, 5]
>>> [x*x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x**2 for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x*x for x in range(11) if x % 2 ==0]
[0, 4, 16, 36, 64, 100]
>>> [x*x for x in range(11) if x % 2 <> 0]
[1, 9, 25, 49, 81]
>>> [a+b for a in 'ABC' for b in '123']
['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']
>>> [a+b+c for a in 'HI' for b in 'JOE' if b!= 'E' for c in '123' if c!='2']
['HJ1', 'HJ3', 'HO1', 'HO3', 'IJ1', 'IJ3', 'IO1', 'IO3']
>>> [(x, ord(x)) for x in 'Ouch']
[('O', 79), ('u', 117), ('c', 99), ('h', 104)]
>>>

创建元组

>>> x= ()
>>> y = 22047,'Fredericksburg'
>>> z= ("mrs.white",'Ballroom',"candless")
>>> x = ("lonely",)
>>> tuple('tuple')
('t', 'u', 'p', 'l', 'e')
>>> tuple([1,2,3])
(1, 2, 3)

运算 *表示重复,扩充运算之起创建新对象的作用

>>> [1,2]+[5]+['REFGGG']
[1, 2, 5, 'REFGGG']
>>> ('fang',)+(17,18)
('fang', 17, 18)
>>> (1,3+4j)*2
(1, (3+4j), 1, (3+4j))
>>> z = ["bow","arrow"]
>>> z*=2
>>> z
['bow', 'arrow', 'bow', 'arrow']
>>> q=(1,2)
>>> q+=(3,4)
>>> q
(1, 2, 3, 4)
>>>


比较

>>> ['five','tow']!= [5,2]
True
>>> ['five','tow']!= [2,5]
True
>>> (0.5,2)<(0.5,1)
False
>>> (0.5,2)>(0.5,1)
True
>>> trouble = ('Dan','Joe','Bob')
>>> 'Bob' in trouble
True
>>> 'dave' not in trouble
True

切片 namelist(strat:end)

>>> meses = ['sdfds','dsfds','ewrew','werew']
>>> meses[1:3]
['dsfds', 'ewrew']
>>> meses[1:-2]
['dsfds']
>>>

解包

>>> s = 801,952,565
>>> x,y,z =s
>>> print x,y,z
801 952 565

一些相关函数

>>> for op in ['sim','cos','tan']:
 print op

sim
cos
tan
>>> data = [0.5,12,18,5,-5]
>>> len(data)
5
>>> min(data)
-5
>>> max(data)
18

※filter(function,list)
>>> def nukebad(s):
 return s.find('bad')==-1

>>> s= ['bad','good','sinbad','bade','welcome']
>>> filter(nukebad,s)
['good', 'welcome']

>>> stuff = [12,0,'hek',[],'',[1,2]]
>>> filter(None,stuff)
[12, 'hek', [1, 2]]

>>> filter(lambda d:not d.isdigit(),"py90thon324")
'python'

※map(function,list[,list,...])

>>> import string
>>> s = ['chile','canada','mexico']
>>> map(string.capitalize,s)
['Chile', 'Canada', 'Mexico']
>>>

>>> import operator
>>> s = [1,3,2,4];t = [5,6,7,8]
>>> map(operator.mul,s,t) # s[j] * t[j]
[5, 18, 14, 32]
※reduce(function,seq[,init])
>>> import operator
>>> reduce(operator.mul,[2,3,4,5])
120
>>> # 120=((2*3)*4)*5
>>> reduce(lambda x,y:x+y,'hello','-')
'-hello'
>>> reduce(lambda x,y:y+x+y,'hello','-')
'olleh-hello'
>>> reduce(lambda x,y:y+x,'hello','-')
'olleh-'
>>> reduce(lambda x,y:y,'hello','-')
'o'
>>> reduce(lambda x,y:x,'hello','-')
'-'
>>> reduce(lambda x,y:x+y+x,'hello','-')
'-h-e-h-l-h-e-h-l-h-e-h-l-h-e-h-o-h-e-h-l-h-e-h-l-h-

e-h-l-h-e-h-'
>>>
※zip(seq[,seq,...])
>>> names = ['Joe','Fred','Sam']
>>> exts = [116,120,100]
>>> ages = [26,34,28]
>>> for name,ext,age in zip(names,exts,ages):
 print '%s(extension %d)is %d'%(name,ext,age)

Joe(extension 116)is 26
Fred(extension 120)is 34
Sam(extension 100)is 28
>>> zip((1,2,3,4))
[(1,), (2,), (3,), (4,)]
替换、删除
替换直接给切片赋值
删除使用函数del namelist[num]
4、列表的一些函数方法
※append(obj)和extend(obj)
>>> z = ['Nevada','Virginia']
>>> z.append('utab')
>>> z
['Nevada', 'Virginia', 'utab']
>>> z.extend(['north carolina','georgia'])
>>> z
['Nevada', 'Virginia', 'utab', 'north carolina',

'georgia']
>>>
※index(obj)
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> z = range(10)
>>> z
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> z.index(2)
2
>>> z.index(12)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    z.index(12)
ValueError: list.index(x): x not in list
>>>
※count(obj)
>>> z = range(5)
>>> z
[0, 1, 2, 3, 4]
>>> z.count(2)
1
>>> z.count(6)
0
>>>
※insert(j,obj)
>>> months = ['march','may','june']
>>> months.insert(1,'april')
>>> months
['march', 'april', 'may', 'june']
>>>
>>> months.insert(-1,'fe')
>>> months.insert(500,'fedsf')
>>> months
['march', 'april', 'may', 'fe', 'june', 'fedsf']
※remove(obj)
>>> months.remove('march')
>>> months
['april', 'may', 'fe', 'june', 'fedsf']
>>>
※pop[j]
>>> saludos = ['1','2','3','4']
>>> saludos.pop(1)
'2'
>>> saludos
['1', '3', '4']
>>> saludos.pop()
'4'
>>> saludos
['1', '3']
※reverse()
>>> names= ['1','3','2','4']
>>> names.reverse()
>>> names
['4', '2', '3', '1']
※sort([func])
>>> names.sort()
>>> names
['1', '2', '3', '4']
>>> names= ['javsa','delphi','pb','vc++']
>>> names.sort(lambda a,b:len(a)-len(b))
>>> names
['pb', 'vc++', 'javsa', 'delphi']
>>>
5、词典
(创建词典)
>>> logins =

{'yahoo':('john','jyahoohn'),'hotmail':('dsfds','dsf

')}
>>> logins['hotmail']
('dsfds', 'dsf')
>>>
(添加项目)
>>> logins['slq']=('select','delete')
>>> logins
{'hotmail': ('dsfds', 'dsf'), 'yahoo': ('john',

'jyahoohn'), 'slq': ('select', 'delete')}
(访问词典)
>>> logins.get('slq')
('select', 'delete')
>>> logins.get('slq') == None
False
>>> logins.setdefault('sql',('nihao','wohao'))
('nihao', 'wohao')
>>> logins.setdefault('slq',('nihao','wohao'))
('select', 'delete')
>>> 
※has_key(key)
>>> logins.has_key('yahoo')
True
>>> del logins['yahoo']
>>> logins.has_key('yahoo')
False
>>>

>>> hash('hash')
-1671425852
>>> hash(10)
10
>>> hash(10.00)
10
>>> hash((1,2,3))
-378539185

将一个词典添加到另一个词典中

>>> z={}
>>> z['slashdot']=('fread','fred')
>>> z.update(logins)
>>> logins
{'hotmail': ('dsfds', 'dsf'), 'sql': ('nihao', 'wohao'), 'slq': ('select', 'delete')}
>>> z
{'hotmail': ('dsfds', 'dsf'), 'slashdot': ('fread', 'fred'), 'slq': ('select', 'delete'), 'sql': ('nihao', 'wohao')}
>>>

一些重要的函数,简单而有用 

>>>z.keys()
['hotmail', 'slashdot', 'slq', 'sql']
>>> logins.keys()
['hotmail', 'sql', 'slq']
>>> logins.values()
[('dsfds', 'dsf'), ('nihao', 'wohao'), ('select', 'delete')]
>>> z.values()
[('dsfds', 'dsf'), ('fread', 'fred'), ('select', 'delete'), ('nihao', 'wohao')]
>>> logins.items()
[('hotmail', ('dsfds', 'dsf')), ('sql', ('nihao', 'wohao')), ('slq', ('select', 'delete'))]
>>> logins.clear()
>>> logins
{}
>>>

>>> d={'one':1,'two':2,'three':3}
>>> b = d.copy()
>>> b
{'one': 1, 'three': 3, 'two': 2}
>>>

引用

>>> shoppinglist= ['candy','cookies','ice cream']

#id(obj)检索对象的身份(身份是指内存中对象的地址)
>>> id(shoppinglist)
11078192
>>> id(5)
9133320
>>>
>>> junkFood = shoppinglist

#is运算符用于比较两个对象的身份,以查看它们是否相同:
>>> junkFood is  shoppinglist
True
>>>

由于变量只引用对象,所以更改可变对象的值,对于引用该对象的所有变量而言,是可见的:

>>> a=[1,2,3,4]
>>> b=a
>>> a[2]=5
>>> b
[1, 2, 5, 4]
>>> a=6
>>> v=a
>>> v
6
>>> a+=1
>>> v
6
>>> a
7
>>>

浅副本

>>> faceCards = ['a','k','q','j']
>>> myHand = faceCards[:]
>>> myHand is faceCards
False
>>> myHand == faceCards
True
>>>
>>> import copy
>>> highCards = copy.copy(faceCards)
>>> highCards is faceCards, highCards == faceCards
(False, True)
>>>

深副本

深(Deep)副本能够生成包容器对象的副本,并递归地生成所有子对象的副本。
例如,考虑列表包含另一个列表的情况。父列表的浅副本将包含对子对象的引用,而不

是独立副本。其结果是,当更改内部列表时,从父列表的两个副本中都可见:
>>> MyAccount = [1000,['Checking','Savings']]
>>> YourAccount = MyAccount[:]
>>> MyAccount[1].remove('Savings')
>>> MyAccount
[1000, ['Checking']]
>>> YourAccount
[1000, ['Checking']]
>>>
copy模块中的deepcopy(obj)
>>> MyAccount = [1000,['Checking','Savings']]
>>> YourAccount = copy.deepcopy(MyAccount)
>>> MyAccount[1].remove('Savings')
>>> MyAccount
[1000, ['Checking']]
>>> YourAccount
[1000, ['Checking', 'Savings']]
>>>
deepcopy函数用于跟踪它复制的对象,以便在对象直接或者间接引用它自身时,deepcop

y仅生成该对象的一个副本。
并不是所有的对象都可以安全地进行复制。例如,把具有开放式连接的套接字赋值复制

到远程计算机中就不会运行,这是由于对象的部分内部状态(开放式连接)位于Python

的领域之外。文件对象是禁止复制领域的另一个示例,而且Python会让用户知道:
type(obj)可以查看数据类型,这个模块包含Python的内置数据类型的类型对象。
>>> type(5)
<type></type>
>>> type("she sells seashells")
<type></type>
>>> type(copy)
<type></type>
>>> import operator
>>> type(operator)
<type></type>
>>>
例:
>>> import types
>>> def upEm(Words):
 if type(Words)!= types.ListType:
  Words = [Words]
 for Word in Words:
  print Word.upper()

>>> upEm('horse')
HORSE
>>> upEm(['horse','cow','sheep'])
HORSE
COW
SHEEP
>>>
下面的列表给出了可以使用的几个
BuiltinFunctionType
FunctionType
MethodType
BuiltinMethodType
InstanceType
ModuleType
ClassType
IntType
NoneType
DictType
LambdaType
StringType
FileType
ListType
TupleType
FloatType
LongType
类和类的实例分别具有ClassType和InstanceType类型。Python提供了isinstance(obj)

函数和issubclass(obj)函数,以测试某个对象是实例还是特殊类型的子类:
>>> isinstance(5.1,types.FloatType)
True
>>> class Foo:
 pass

>>> s = Foo()
>>> isinstance(s,Foo)
True

创建数组
>>> import array
>>> z = array.array('B')
>>> z.append(5)
>>> z[0]
5
>>> q = array.array('i',[5,-10,12,-13])
>>> q
array('i', [5, -10, 12, -13])
>>>
数组类型代码

>>> q.itemsize
4

类型转换

数组转换成列表

>>> q.tolist
<built-in tolist="" of="" array.array="" object="" at="" method=""></built-in>

 

fromlist(list)方法把常规列表中的项附加到数组的末尾

>>> q.fromlist([2,4])
>>> q
array('i', [5, -10, 12, -13, 2, 4])

tostring()方法,把数组转换成字符串。

>>> q.tostring()
'\x05\x00\x00\x00\xf6\xff\xff\xff\x0c\x00\x00\x00\xf3\xff\xff\xff\x02\x00\x00\x00\x04\x00\x00\x00'
>>> len(q.tostring())
24

fromstring(str)方法将进行反方向的操作,获取一个字节串,并把他们转化成为数组的值:

>>> q.fromstring('\x10\x00\x00\x02')
>>> q
array('i', [5, -10, 12, -13, 2, 4, 33554448])
>>>

tofile(file)方法把数组转换为字节的序列(如tostring),并把结果字节写入所传递的文件中:

>>> z= array.array('h',[10,1000,500])
>>> f = open('myarray','wb')
>>> z.tofile(f)
>>> f.close()

fromfile(file,count)方法用于从文件对象中读取特定数目的项,并把他们附加到数组中

>>> z.fromfile(open('myarray','rb'),3)
>>> z
array('h', [10, 1000, 500, 10, 1000, 500])
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics