Python学习(三)——————基础知识汇总(三)

接Python学习(三)——————基础知识汇总(二)

3. 列表:

列表是序列操作的一种,那么它适用上一节说的所有序列的那些操作,除此之外列表的优势是他可以更改列表元素的值,上节所说的字符串不能够更改内容的,后面要讲的元组也是不可以更改的,只有列表是最随意操作的数据结构。下面还是用代码来解释每个数据操作方式,重点的地方我会在其中注释:

>>> al = [ 123, 'abc' , 4.5 , [ 'in' , 'list' ] , 7-9j ]
>>> al
[123, 'abc', 4.5, ['in', 'list'], (7-9j)]
>>> print al
[123, 'abc', 4.5, ['in', 'list'], (7-9j)]
>>> 123 in al
True
>>> 'abc' in al
True
>>> ['in' , 'list'] in al
True
>>> bl = [ None , 'sth to see' ] 
>>> bl
[None, 'sth to see']
>>> list(123)
Traceback (most recent call last):
  File "
    
    
     
     ", line 1, in 
     
     
      
      
TypeError: 'int' object is not iterable
>>> list('fore')
['f', 'o', 'r', 'e']
>>> list

      
      
       
       
>>> al[0]
123
>>> al[-1]
(7-9j)
>>> al[:3]
[123, 'abc', 4.5]
>>> al[3]
['in', 'list']
>>> al[3][1]
'list'
>>> 
>>> 
>>> al[2] = 9
>>> al
[123, 'abc', 9, ['in', 'list'], (7-9j)]
>>> al[2] = 'dh'
>>> al
[123, 'abc', 'dh', ['in', 'list'], (7-9j)]
>>> al.append(13)
>>> la
Traceback (most recent call last):
  File "
       
       
        
        ", line 1, in 
        
        
          NameError: name 'la' is not defined >>> al [123, 'abc', 'dh', ['in', 'list'], (7-9j), 13] >>> >>> >>> del al[1] >>> al [123, 'dh', ['in', 'list'], (7-9j), 13] >>> al.remove(13) >>> al [123, 'dh', ['in', 'list'], (7-9j)] >>> al.remove('akk') Traceback (most recent call last): File " 
         
           ", line 1, in 
          
            ValueError: list.remove(x): x not in list >>> al.remove('list') Traceback (most recent call last): File " 
           
             ", line 1, in 
            
              ValueError: list.remove(x): x not in list >>> al*2 [123, 'dh', ['in', 'list'], (7-9j), 123, 'dh', ['in', 'list'], (7-9j)] >>> >>> >>> >>> [ i*2 for i in [ 1,2,3] ] [2, 4, 6] >>> al [123, 'dh', ['in', 'list'], (7-9j)] >>> tuple(al) (123, 'dh', ['in', 'list'], (7-9j)) >>> al [123, 'dh', ['in', 'list'], (7-9j)] >>> list('123',45) Traceback (most recent call last): File " 
             
               ", line 1, in 
              
                TypeError: list() takes at most 1 argument (2 given) >>> 
               
              
             
            
           
          
        
       
       
      
      
     
     
    
    
下面贴上list的内建函数也都是很常见的函数,使用不祥述了



4、元组
元组跟列表简直就是孪生兄弟,从功能上讲列表能做的元组也能做,元组的声明方式是使用圆括弧,列表是使用方括弧。元组和列表的很重要的区别就是元组是不可更改的,刚才的代码可以看到列表可以随便索引到值之后对其进行赋值,这个操作对于字符串和元组都是不可以。也就是说如果你有个列表要传递给别人操作,而你又担心他会无意中修改,那么最好的方式就是你把他转化成元组然后再传递给他。(当然了,他如果要改也不是不可能的,完全可以去掉要删的,重组一个新的列表,但对象就变了,这个变化是可以通过id看到滴),上代码:
>>> at = ( 123 , 'abc' , 4.5 , [ 'in' , 'tuple' ] , ('t' , 1) , 7-9j )
>>> at
(123, 'abc', 4.5, ['in', 'tuple'], ('t', 1), (7-9j))
>>> print at
(123, 'abc', 4.5, ['in', 'tuple'], ('t', 1), (7-9j))
>>> at[0]
123
>>> at[-1]
(7-9j)
>>> at[-2]
('t', 1)
>>> at[-2][-1]
1
>>> tuple('foo')
('f', 'o', 'o')
>>> tuple(123)
Traceback (most recent call last):
  File "
     
     
      
      ", line 1, in 
      
      
       
       
TypeError: 'int' object is not iterable
>>> a = 1
>>> tuple(a)
Traceback (most recent call last):
  File "
       
       
        
        ", line 1, in 
        
        
         
         
TypeError: 'int' object is not iterable
>>> at[:4]
(123, 'abc', 4.5, ['in', 'tuple'])
>>> at[::2]
(123, 4.5, ('t', 1))
>>> 
>>> 
>>> at = at[0],at[3]
>>> at
(123, ['in', 'tuple'])
>>> at[0] = 123
Traceback (most recent call last):
  File "
         
         
           ", line 1, in 
          
            TypeError: 'tuple' object does not support item assignment >>> at1 = 123,'abc' >>> at1 (123, 'abc') >>> at2 = 456,'efg' >>> at3 = at1+at2 >>> at3 (123, 'abc', 456, 'efg') >>> at3 = at3,at2 >>> at3 ((123, 'abc', 456, 'efg'), (456, 'efg')) >>> >>> >>> >>> str(at3) "((123, 'abc', 456, 'efg'), (456, 'efg'))" >>> len(at3) 2 >>> max(at3) (456, 'efg') >>> min(at3) (123, 'abc', 456, 'efg') >>> list(at3) [(123, 'abc', 456, 'efg'), (456, 'efg')] >>> >>> at = (123,'abc') >>> at[1] = 'efg' Traceback (most recent call last): File " 
           
             ", line 1, in 
            
              TypeError: 'tuple' object does not support item assignment >>> id(at) 4349479896 >>> at = at[0],'efg' >>> at (123, 'efg') >>> id(at) 4349480616 >>> >>> def test(): ... return 'abc',123 ... >>> a = test() >>> a ('abc', 123) >>> a,b = test() >>> a 'abc' >>> b 123 >>> def test(): ... return ('abc',123) ... >>> a = test() >>> a ('abc', 123) >>> a,b = test() >>> a 'abc' >>> b 123 >>> >>> a = ['abc'] >>> type(a) 
             
               >>> a = ('abc') >>> type(a) 
              
                >>> print a abc >>> a = ('abc',) >>> type(a) 
               
                 >>> print a ('abc',) >>> 
                
               
              
             
            
           
         
        
        
       
       
      
      
     
     
由于元组本身的数据是不可变的,所以内建方法很少,只有max(),min(),len(),list()转换等。对于其他操作会改变元组元素所以就没有那些内建方法,如果想更新元组:那么只能把整个元组重新赋值,新的值是需要更新的那个元素的新值,其他的值不变。但是这个新的元组已经是新对象了,ID是不一样的(相当于新建了一个元组),见上面的代码演示。如果想删除一个元组元素:可以赋值给这个元组(相当于新建一个不含这个要删除元素的元组)
  1. 有一个要记忆的是当函数返回的时候,如果是多对象,例如return obj1,obj2这其实返回的是元组,他和return (obj1,obj2)是一样的。见代码例子。
2. 当用字符串初始化一个单元素元组时由于会被误认为是个字符串,所以如果想有一个单元素元组要在字符串元素后面加个逗号!见代码

5、字典——非序列数据类型
前面三个说的都是序列数据类型,不论是切片、索引、链接、重复都是序列数据类型的内建操作,现在学习一个不一样的数据类型——字典。顾名思义,跟生活中的字典差不多,一个字典是很多对儿键值对组成的,每个键值对包括一个关键字和对应的值,这个关键字可以是任何可哈希的对象包括字符串、元组、数字,但是字典和列表这种可变值数据不可以哦!(因为他内部用的技术就是哈希),不过一般我们用字符串来做键容易阅读,值可以是任何值。字典用大括号来声明,上代码:

>>> d = { 'name':'abc','port':123 }
>>> d
{'name': 'abc', 'port': 123}
>>> d[0]
Traceback (most recent call last):
  File "
    
    
     
     ", line 1, in 
     
     
      
      
KeyError: 0
>>> d += {'height':567}
Traceback (most recent call last):
  File "
      
      
       
       ", line 1, in 
       
       
        
        
TypeError: unsupported operand type(s) for +=: 'dict' and 'dict'
>>> 
>>> d1 = {}.fromkeys( ('x','y'),-1)
>>> d1
{'y': -1, 'x': -1}
>>> for key in d.keys():
...     print 'key = %s , value = %s ' %(key,d[key])
... 
key = name , value = abc 
key = port , value = 123 
>>> d['name']
'abc'
>>> d.has_key('server')
False
>>> d.has_key('name')
True
>>> 
>>> 
>>> d3 = {}
>>> d3[1] = 8994
>>> d3['name']=abc
Traceback (most recent call last):
  File "
        
        
          ", line 1, in 
         
           NameError: name 'abc' is not defined >>> d3['name']='abc' >>> d3 {1: 8994, 'name': 'abc'} >>> d3[1]=1111 >>> d3 {1: 1111, 'name': 'abc'} >>> d3[2] = ('ac',23) >>> d3 {1: 1111, 2: ('ac', 23), 'name': 'abc'} >>> d3[ (123,456) ] = '123' >>> d3 {(123, 456): '123', 1: 1111, 2: ('ac', 23), 'name': 'abc'} >>> d3[ ['ddf',123] ] = '12093' Traceback (most recent call last): File " 
          
            ", line 1, in 
           
             TypeError: unhashable type: 'list' >>> >>> >>> del d3[1] >>> d3 {(123, 456): '123', 2: ('ac', 23), 'name': 'abc'} >>> d3.pop(2) ('ac', 23) >>> d3 {(123, 456): '123', 'name': 'abc'} >>> >>> d = {'host':1,'server':'abc','port':888} >>> d.keys() ['host', 'port', 'server'] >>> d.values() [1, 888, 'abc'] >>> d.items() [('host', 1), ('port', 888), ('server', 'abc')] >>> 
            
           
          
        
       
       
      
      
     
     
    
    

附上常用的字典的内建函数:



6、集合
集合的生成只有使用内建方法set() 和 frozenset()来生成,集合也是常用的数据类型。集合数据结构十分常用,它包含了常用的集合的数学操作包括子集,交集,并集,异或集等等,用于多数据的交叉计算和分析,代码例子中有一个是分析词语的交叉分析例子,具体使用看代码:
>>> s = set('cheeeeepsesertre')
>>> s
set(['c', 'e', 'h', 'p', 's', 'r', 't'])
>>> t = frozenset('bookshop')
>>> t
frozenset(['b', 'h', 'k', 'o', 'p', 's'])
>>> len(s)
7
>>> len(t)
6
>>> 'c' in s
True
>>> 'c' in t
False
>>> s.add('z')
>>> s
set(['c', 'e', 'h', 'p', 's', 'r', 't', 'z'])
>>> s.add('c')
>>> s
set(['c', 'e', 'h', 'p', 's', 'r', 't', 'z'])
>>> s.update('python123')
>>> s
set(['c', 'e', 'h', '3', 'o', 'n', '1', 'p', 's', 'r', 't', 'y', '2', 'z'])
>>> s.remove('c')
>>> s
set(['e', 'h', '3', 'o', 'n', '1', 'p', 's', 'r', 't', 'y', '2', 'z'])
>>> s -= set('python123')
>>> s
set(['e', 's', 'r', 'z'])
>>> s&t
set(['s'])
>>> s | t
set(['b', 'e', 'h', 'k', 'o', 'p', 's', 'r', 'z'])
>>> s - t
set(['r', 'e', 'z'])
>>> s ^ t
set(['p', 'b', 'e', 'z', 'h', 'k', 'r', 'o'])
>>> 

>>> a = set( [ 'this','is','article','one' ])
>>> b = set( [ 'that','article','is','this','one'] )
>>> a
set(['this', 'article', 'is', 'one'])
>>> b
set(['this', 'article', 'is', 'one', 'that'])
>>> 'this' in a
True
>>> a == b
False
>>> a != b
True
>>> a < b
True
>>> a & b 
set(['this', 'article', 'is', 'one'])
>>> a & b == a
True
>>> a | b
set(['that', 'this', 'is', 'one', 'article'])
>>> a - b 
set([])
>>> a ^ b
set(['that'])
>>> b - a
set(['that'])
>>> 

对于集合的内建对象的操作符和函数如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值