Python从入门到进阶(八)——语法基础(五)

Python基本数据类型 list,tuple,dict,set

数据类型表示方法特性
list列表用方括号表示:[]list是一种有序的集合,可以随时添加和删除其中的元素,和C++数组区别就是类型可不同
tuple元组用圆括号表示:()和list相比唯一的差异在于元组是只读的,不能修改
dict字典用花括号表示:{}列表是有序的对象结合,字典是无序的对象集合,两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取.
setset()集合是一个无序不重复元素集,基本功能包括关系测试和消除重复元素

1 列表list

1.1 初始化列表

  • 指定元素初始化列表
num=['aa','bb','cc',1,2,3]
print num
['aa','bb','cc',1,2,3]
  • 从字符串初始化列表
a='oiawoidhoawd97192048f'
num=list(a)
print num
['o', 'i', 'a', 'w', 'o', 'i', 'd', 'h', 'o', 'a', 'w', 'd', '9', '7', '1', '9', '2', '0', '4', '8', 'f']
  • 从元组初始化列表
a=(1,2,3,4,5,6,7,8)
num=list(a)
print num
[1, 2, 3, 4, 5, 6, 7, 8]
  • 创建一个空列表
num=[]
print num
[]
  • 用某个固定值初始化列表
intial_value=0
    list_length=5
    sample_list=[intial_value]*list_length
    print(sample_list)
    sample_list=[intial_value for i in range(10)]
    print(sample_list)
 [0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]   

1.2 访问列表

  • 访问单个元素
num=[0,1,2,3,4,5,6,7]
    print(num[3])
    print(num[0])
    print(num[-1])
    print(num[-3])
3
0
7
5
  • 遍历整个列表
num=[0,1,2,3,4,5,6,7]
    for a in num:
        print(a)

    for i in range(len(num)):
        print(num[i])

2 列表操作

2.1 更新列表

num=[0,1,2,3,4,5,6,7]
    num[1]='abc'
    print(num)
 [0, 'abc', 2, 3, 4, 5, 6, 7]   

2.2 删除列表元素

num=[0,1,2,3,4,5,6,7]
    for i in range(len(num)):
        print(num[i])
    del num[2]
    print(num)

输出结果:0 1 2 3 4 5 6 7 [0, 1, 3, 4, 5, 6, 7]

2.3 列表操作符+*

列表对+和的操作符与字符串相似,+用于组合列表,*号用于重复列表
以下为+操作符

>>> a=['a','b','c']
>>> b=['d','e','f']
>>> c=a+b
>>> print c
['a', 'b', 'c', 'd', 'e', 'f']

以下为*操作符

>>> a=['a','b','c']
>>> c=a*4
>>> print c
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

以下是help(list)的结果中关于重点函数的介绍部分

Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

3 元组tuple

Python的元组与列表类似,不同之处在于元组的元素不能修改;元组使用小括号(),列表使用方括号[];元组创建很简单,只需要在括号中添加元素,并使用(,)隔开

3.1 元组初始化

t=(1,2,3)
    print(t)
    t=tuple(range(3))
    print(t)
(1,2,3)
(0,1,2)

3.2 元组函数

关于tuple相关的函数可以使用help命令获得
help(tuple)

Help on class tuple in module builtins:

class tuple(object)
 |  tuple() -> empty tuple
 |  tuple(iterable) -> tuple initialized from iterable's items
 |  
 |  If the argument is a tuple, the return value is the same object.
 |  
 |  Methods defined here:
 |  
 |  count(...)
 |      T.count(value) -> integer -- return number of occurrences of value
 |  
 |  index(...)
 |      T.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.

list和index方法的使用和list一模一样

3.3 命名元组

Python有一个类似tuple的容器nametuples(命名元组),位于collection模块中.namedtuple是继承自tuple的子类,可创建一个和tuple类似的对象,而且对象拥有可访问的属性
在Python中起相同作用的就是命名元组了

# 命名元组
    from collections import namedtuple
    Point=namedtuple('Point','x,y')
    p1=Point(11,y=22)
    print(p1)

    type(p1)
    p1.x
    p1.y
    p1[0]+p1[1]
    a,b=p1
    print(a,b)

4 字典

可以发现,dict是python內建的类,是一种key-value结构

Help on class dict in module __builtin__:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:

字典是除列表之外Python中最灵活的内置数据结构类型,列表是有序的对象结合,字典是无序的对象集合.两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取.

dict={'Alice':'2341','Beth':'9102','Cecil':'3258'}

每个键与值必须用冒号隔开,每对用逗号分隔,整体放在花括号中({}).键必须独一无二,但值则不必;值可以取任何数据类型,但必须是不可变的,如字符串,数或元组.

4.1 字典初始化

	d={}
    print(type(d))
    d=dict()
    d={'a':1,'b':2}

    d=dict([('a',1),('b',2)]) # 可接受以元组为元素的列表

    print(d)

    d=dict.fromkeys(range(5)) # 传入的可迭代元素为key,值为None

    print(d)

    d=dict.fromkeys(range(5),'abc') # 传入的可迭代元素为key,值为'abc'

    print(d)

<class 'dict'>
{'a': 1, 'b': 2}
{0: None, 1: None, 2: None, 3: None, 4: None}
{0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc'}

4.2 增加

d[key]=value,update

d={0:'abc',1:'abc',2:'abc',3:'abc',4:'abc'}

    print(d)

    d['a']=1 # 可以直接使用key作为下标,对某个不存在的下标赋值,会增加kv对
    print(d)

    d.update([('c',3),('p',0)]) # update 传入的参数需要和dict保持一致

    print(d)

    d.update([('c',4),('p',4)]) # 对已经存在的update时会进行修改,通常用于合并字典

    print(d)

{0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc'}
{0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'a': 1}
{0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'a': 1, 'c': 3, 'p': 0}
{0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc', 'a': 1, 'c': 4, 'p': 4}

4.3 删除

  • pop用于从字典删除一个key,并返回其value,当删除不存在key时,会抛出keyError.当指定默认值时,删除不存在值,会返回默认值且不抛出keyError
  • popitem随机返回并删除一个kv对的二元组
  • clear 清空一个字典
  • del语句
d={0:'abc',1:'abc',2:'abc',3:'abc',4:'abc','p':4,'c':4,'a':1}
    help(d.pop)

    d.pop(0) # 删除key,并返回value

    print(d)

    d.pop(0) # 如果要删除的Key不存在,抛出KeyError

    d.pop(0,'default') # 给定default,删除不存在key返回default

    d.pop(1,'default') # 给定的default对存在的key不会产生影响
    
    d.pop(1,'abc')

    print(d)

4.4 访问

单个元素访问

-通过key直接访问
-通过get函数访问

 d={'r':2,'d':2,'c':3,'p':0}

    print(d)

    print(d['p'])
    print(d['c'])
    print(d['a']) # KeyError

    print(d.get('d'))
    print(d.get('a')) # KeyError
    print(d.get('a','default'))

    help(d.setdefault)
    d.setdefault('c','default')
    d.setdefault('a','default')

    print(d)

4.5 字典的遍历

  1. 直接for in 遍历
for x in d:
	print(x)

直接用for in遍历字典,遍历的是字典的key

  1. keys函数遍历
  • d.keys() # keys方法返回一个可迭代对象,元素是字典的所有key
  • d.keys() -> dict_keys([‘d’,‘a’,‘c’,‘r’,‘p’])
for x in d.keys():
	print(x)
  1. values函数遍历
  • d.values() # values方法返回一个可迭代对象,元素是字典所有的value
  • d.values() ->dict_values([2,‘default’,3,2,0]])
for x in d.values():
	print(x)
  1. items函数遍历
  • d.items() # items方法返回一个可迭代对象,元素是字典的所有(k,v)对
  • d.items() ->dict_items([(‘d’,2),(‘a’,‘default’,(‘c’,3),(‘r’,2),(‘p’,0))])
for x in d.items():
	print(x)

另外一种方式:解析(k,v)对

for k,v in d.items();
	print(k,v)

keys,values,items返回的都类似生成器的对象,它并不会复制一份内存
Python2对应的函数返回的是列表,会复制一份内存

4.6 字典的限制

  • 字典的key不能重复
  • 字典的key需要可hash

4.7 默认字典

默认字典是defaultdict

from collections import defaultdict
d1={}
print(d1)
d2=defaultdict(list) # list在此是list的初始化函数
print(d2)
defaultdict(list,{})
# print(d1['a']) # KeyError
print(d2['a'])

{}
defaultdict(<class 'list'>, {})
[]

default初始化的时候,需要传入一个工厂函数,具体的介绍可以使用help(defaultdict)来查看,当使用下标访问一个key的时候,如果这个key不存在,defaultdict会自动调用初始化时传入的函数,生成一个对象作为这个key的value.因此上面的list函数初始化的时候就生成了一个空列表.
以下是使用dict和defaultdict的对比

 for k in range(10):
        for v in range(10):
            if k not in d.keys():
                d[k]=[]
            d[k].append(v)

如果用defaultdict来写

d=defaultdict(list)
    for k in range(10):
        for v in range(10):
            d[k].append(v)

4.8 有序字典

有序字典是OrderedDict(第一个字母大写)

# 有序字典 OrderedDict (第一个字母大写)
def testyxzd():
    from collections import OrderedDict
    d=OrderedDict()
    d[0]=3
    d[3]=4
    d[1]=5
    print(d)

    for k,v in d.items():
        print(k,v)
    pass

5 集合set

>>> help(set)
Help on class set in module __builtin__:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |  
 |  Build an unordered collection of unique elements.
 |  
 |  Methods defined here:
def testSet():
    a=[11,22,33,44,11,22]
    b=set(a)
    print(b)
    set([33,11,44,22])
    c=[i for i in b]
    print(c)
    pass

if __name__ == '__main__':
    testSet()

{33, 11, 44, 22}
[33, 11, 44, 22]

5.1 定义与初始化

def testdySet():
    s=set()
    print(s)
    s={1,2,3}
    print(s)
    s=set(range(3))
    print(s)
    pass

if __name__ == '__main__':
    testdySet()

set()
{1, 2, 3}
{0, 1, 2}

5.2 增加

增加函数有两个add和update
add是增加单个元素,和列表的append操作类似,是原地修改
update是增加一个可迭代对象,和列表的extend操作类似,是原地修改
两个函数对于已经存在的元素会什么也不做

def testaddupdateset():
    s={0,1,2}
    s.add(3)
    print(s)
    help(s.update)
    s.update(range(4,7))
    s={0,1,2,3,4,5,6}
    s.update(range(4,9))
    print(s)
    pass

if __name__ == '__main__':
    testaddupdateset()

{0, 1, 2, 3}
Help on built-in function update:

update(...) method of builtins.set instance
    Update a set with the union of itself and others.

{0, 1, 2, 3, 4, 5, 6, 7, 8}

5.3 删除

  • remove 删除给定的元素,元素不存在抛出KeyError(需要抛出异常时使用此函数)
  • discard 删除给定的元素,元素不存在,什么也不做(和remove的唯一区别)
  • pop随机随机arbitrary删除一个元素并返回,集合为空,抛出KeyError
  • clear 清空集合
def testDelset():
    s={0,1,2,3,4,5,6,7,8}
    s.remove(0)
    print(s)

    #s.remove(10) # KeyError
    s.discard(10)
    print(s)
    help(s.pop)
    s.pop()
    s.pop()
    s.clear()
    #s.pop() # KeyError

    pass

if __name__ == '__main__':
    testDelset()

5.4 修改

集合不能修改单个元素

5.5 查找

  • 集合不能通过索引
  • 集合没有访问单个元素的方法
  • 集合不是线性结构,集合元素没有顺序

集合的pop操作的随机性可以证明集合不是线性结构的.

s={1,2,3,4,5,65,66,67,88}
print(s.pop())
65

6 成员运算符

  • in
  • not in
    用来判断一个元素是否在容器中
	1 in [1,2,3,4] 
    5 in [1,2,3,4] # False
    5 not in [1,2,3,4]
    'love' in 'I love python'
    [1,2] in [1,2,3,4] # False
    1 in (1,2,3,4)
    1 in {1,2,3,4}

集合的成员运算和其他线性结构的时间复杂度不同
做成员运算时,集合效率远高于列表
做成员运算时,列表的效率和列表的规模有关,而集合的效率和集合的规模无关.
成员运算:

  • 集合O(1)
  • 列表(线性结构)O(n)

集合运算

集合运算主要有:交集,差集,对称差集,并集
python中的集合运算都对应两个版本,一个默认版本(返回新的集合),一个update版本(会更新集合本身)

  1. 交集
    intersection
    交集特性:满足交换律,重载了&运算符
s1={1,2,3}
s2={2,3,4}
s1.intersection(s2)
s2.intersection(s1)
s1.intersection_update(s2)  # 交集的update版本,做原地修改,返回none,相当于s1=s1.intersection(s2)
print(s1)
print(s2)
s1={1,2,3}
s1&s2 # 交集重载了&运算符,相当于s1.intersection(s2)
  1. 差集
    差集特性:不满足交换律,重载了-运算符
s1={1,2,3}
s2={2,3,4}
s1.difference(s2) # 1
s2.difference(s1) # 差集不满足交换律 4
s1.difference_update(s2) # 差集的update版本,相当于s1=s1.difference(s2)
s1={1,2,3}
s1-s2 # 差集重载了-运算符,相当于s1.difference(s2)
s2-s1 # 4

  1. 对称差集
    symmetric_difference
    对称差集特性:满足交换律,重载了^运算符
s1={1,2,3}
s2={2,3,4}
s1.symmetric_difference(s2) # {1,4}
s2.symmetric_difference(s1) # {1,4} 满足交换律
s1.symmetric_difference(s2) # 对称差集的update版本,相当于s1=s1.symmetric_difference(s2) {1,4}
s1={1,2,3}
s1^s2 # 对称差集重载了^运算符,相当于s1.symmetric_difference(s2)
  1. 并集
    union,update
    并集特性:满足交换律,重载了I运算符
def testunion():
    # 并集
    s1={1,2,3}
    s2={2,3,4}
    print(s1.union(s2))
    print(s2.union(s1))
    s1.update(s2)
    print(s1)
    s1={1,2,3}
    print(s1|s2) # 并集重载的预算符是|
    pass

{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4}
  1. 集合相关的判断
    issuperset,issubset
    isdisjoint:判断是否两个集合是否不相交(disjoint),有交集则返回False,没有交集则返回True
def testissuperset():
    # 集合相关的判断
    # issuperset,issubset
    # isdisjoint
    s1={1,2,3,4}
    s2={1,2}
    print(s1.issuperset(s2)) # 判断是否是超集
    print(s2.issubset(s1)) # 判断是否是子集
    print(s1.isdisjoint(s2)) # 判断是否不相交
    s1={1,2}
    s2={3,4}
    print(s1.isdisjoint(s2))
    pass
    
if __name__ == '__main__':
    testissuperset()

True
True
False
True
  1. 集合的限制
    集合的元素不能是可变的,集合的元素必须可hash
n [95]: {'a', 'b', 'c'}
Out[95]: {'a', 'b', 'c'}

In [96]: {[1, 2, 3]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-96-e7ef34388120> in <module>()
----> 1 {[1, 2, 3]}

TypeError: unhashable type: 'list'

In [97]: {bytearray(b'abc')}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-97-62b530a8195b> in <module>()
----> 1 {bytearray(b'abc')}

TypeError: unhashable type: 'bytearray'

In [98]: {{3, 4}}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-98-47b1c90a198f> in <module>()
----> 1 {{3, 4}}

TypeError: unhashable type: 'set'

In [99]: {(1, 2)}
Out[99]: {(1, 2)}

In [100]: {b'abc'}
Out[100]: {b'abc'}

#hash函数可以直接使用
In [101]: hash(b'abc')
Out[101]: 1955665834644107130

In [102]: hash([1, 2, 3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-102-0b995650570c> in <module>()
----> 1 hash([1, 2, 3])

TypeError: unhashable type: 'list'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值