1. 元组
元组由不同元素组成,每个元素可以存储不同类型的数据,元组是有序的,元组创建后不能再做任何修改。
元组的创建:
tuple = ('a','b','c','d')
如果创建的元组只有1个元素,需要后面加','逗号,不然python无法区分变量是表达式还是元组,如下案例。
t = ('abc')
print(t[0])
print(type(t))
t1 = ('abc',)
print(t1[0])
print(type(t1))
'''
a
<class 'str'>
abc
<class 'tuple'>
'''
元组的方法:
- index
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
t = (1,2,'d',1,1,1)
#index
print("index:",t.index(1))
print("index:",t.index(1,2,5))
print("count:",t.count(1))
- count
def count(self, value): # real signature unknown; restored from __doc__
""" T.count(value) -> integer -- return number of occurrences of value """
return 0
#count
t = (1,2,'d',1,1,1)
print(t.count(1)) #4
- 取值与切片
元组的下标从0开始,索引的值可以为0、正整数或负整数。
#取值tuple[n]
#切片tuple[m:n]
t = ('abc','def','ghi')
print(t[1]) #def
print(t[1:]) #('def', 'ghi')
print(t[:]) #('abc', 'def', 'ghi')
print(t[0:-2]) #('abc',)
print(t[0:-1]) #('abc', 'def')
- 二元元组
#二元元组
t = ((1,2,3),('a','b','c'))
print(t[0][1])
- 元组的遍历
#元组遍历
t1 = ('zhangsan','lisi',250)
for i in t1:
print(i)
#二元元祖遍历
t2 = (t1,(111,222,'333'))
#遍历方法一
for x in t2:
for y in x: #这里x的类型是tuple
print(y)
#遍历方法二
for x in range(len(t2)):
for y in range(len(t2[x])): #这里x的类型是int
print(t2[x][y])
- 元组的“打包”和“解包”
创建元组的过程,python称为“打包”,“解包”则是将元组的各个元素分别赋值给多个变量。
#元组的打包与解包
t = ('apple','banana','grape','orange')
a,b,c,d = t
print(a,b,c,d) #apple banana grape orange
2. 列表
列表与元组类似,用[]表示,有序的,支持增删改查。
列表的方法:
#列表用一对[]表示
names = ["zhangsan","lisi","wangwu",'zhangsan','1',"2","zhangsan",'a','lisi','b']
print(names)
#append 增加
names.append("cc")
print(names)
#insert 插入
names.insert(1,"dd") #在该下标位置插入元素
print(names)
#切片
na = names[1:3] #顾头不顾尾
print("切片:",na)
#步长切片
na = names[1:5:3] #names[::3]
print("步长切片:",na)
#修改元素
names[1] = 'DD'
print(names)
#reverse反转
names.reverse()
print("reverse:
",names)
#count计数
t = names.count("lisi")
print("count:",t)
#index查看元素下标
t = names.index("lisi") #默认显示查找到的第一个元素的下标
print("index:",t)
t = names.index('lisi',3,10)
print("index:",t)
#extend扩展列表
names2 = ['zhangsan','lisi2','wangwu']
names.extend(names2)
print("extend:
",names)
#也可以使用"+"、"+="进行扩展
names3 = names + names2
print("names+names2:
",names3)
names += names2
print("names+=names2:
",names)
#sort排序
names.sort()
print("sort:
",names)
#删除元素,有三种方法
#1.del 2.remove 3.pop
del names[1] #del names 删除变量
print(names)
names.remove("lisi") #删除第一个lisi
print(names)
names.pop() #默认删除最后一个元素
print(names)
names.pop(2) #加下标就是删除该下标所指的元素
print(names)
#循环列表
for i in names:
print(i)
#len(list)获取列表长度
print("len(names:",len(names))
#clear清空列表
names.clear()
print(names)
enumerate读取下标与内容
#读取列表下标与内容的方法
li = ['a','b','c']
for i in (enumerate(li)):
print(i)
for index,item in enumerate(li):
print(index,item)
print("-------华丽的分割线-------")
#传统方法
for i in li:
print(li.index(i),i)
列表的深浅copy
假设一个列表有多层,比如['a',['b','c'],'d'],那么浅copy只是拷贝了列表的第一层,列表的第二层(更深层的)只是第二层列表的一个引用(内存地址相同)。如果需要完全的拷贝列表,则需要使用深copy,是通过python内置的copy模块来实现的。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#深浅copy,浅copy只拷贝列表第一层元素,更深层的只是一层引用
import copy
#列表赋值,只是列表内存地址的引用
li1 = ['a','b',['A','B','C']]
li2 = li1
li1[1] = 'bb'
li1[2][1] = 'BB'
print(li1,li2) #两个列表完全相同,因为只是内存地址的引用
print("id(li1):",id(li1))
print("id(li2):",id(li2)) #两个列表的内存地址完全一致
#浅copy的几种方法
li3 = li1.copy()
li4 = li1[:]
li5 = copy.copy(li1)
li6 = list(li1) #工厂模式
#查看浅copy的内存
#第二层['A','B','C']无法拷贝,只是一层引用,所以内存地址一样
print(id(li1[2]),id(li3[2]),id(li4[2]),id(li5[2]),id(li6[2]))
print(id(li1[0]),id(li3[0]),id(li4[0]),id(li5[0]),id(li6[0]))
li3[0] = 'a3'
li4[0] = 'a4'
li5[0] = 'a5'
li6[0] = 'a6'
print(id(li1[0]),id(li3[0]),id(li4[0]),id(li5[0]),id(li6[0]))
#深拷贝就是完全复制一份
print("
----浅copy应用----")
stu = ['name',['平均分:',80]]
stu1 = stu.copy()
stu2 = stu[:]
stu3 = copy.copy(stu)
stu4 = list(stu)
stu1[0] = "zhangsan"
stu2[0] = 'lisi'
stu3[0] = 'wangwu'
stu4[0] = '250'
print(stu1)
print(stu2)
print(stu3)
print(stu4)
stu1[1][1] = 90
print(stu1,stu2,stu3,stu4)
print("
======深拷贝======")
l = ['a','b',['A','B',['C','D']]]
l1 = copy.deepcopy(l)
print(id(l),id(l1)) #两个列表内存地址不一致,也就是实现了完全拷贝
l[0] = 'aa'
l1[2][0] = 'AA'
l[2][2][0] = 'CC'
print("l ",l)
print("l1",l1)
列表实现的堆栈和队列
堆栈和队列是数据结构中常用的数据结构,列表可以用来实现堆栈和队列。
堆栈是指最先进入堆栈的元素最后才输出,即“后进先出”。栈的插入、弹出是通过栈首指针控制的。插入一个新的元素,指针移动到新元素的位置;弹出一个元素,指针移到下面一个元素的位置,即原堆栈倒数第二个元素的位置,该元素称为栈顶元素。
队列是指最先进入队列的元素最先输出,即“先进先出”。队列的插入、弹出是分别通过队首指针和队尾指针控制的。插入一个新元素,队尾指针移动到新元素的位置;弹出一个元素,队首指针移动到原队列中第二个元素的位置,该元素称为队列的第一个元素。
通过append()和pop()模拟两种数据结构:
li = ['a','b','c','d']
#先进后出
li.append('e')
print(li.pop()) #e
#先进先出
li.append('f')
print(li.pop(0)) #a
3. 字典
字典是由{}创建,由"键-值"对组成的集合,字典中的"值"通过"键"来引用。字典是无序的,key必须是唯一的,可以增删改查。
字典的方法:
#字典的访问与修改
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
#通过key访问value
print(dic.get('a')) #appale
print(dic['a']) #appale
#修改value
dic['a'] = 'APPALE'
print(dic) #{'a': 'APPALE', 'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog'}
#添加元素
dic.setdefault("e")
print(dic) #{'a': 'APPALE', 'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog', 'e': None}默认value是None
#赋值
dic.setdefault('e','egg')
#添加的同时赋值
dic.setdefault('p','pig')
print(dic)
#{'a': 'APPALE', 'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog', 'e': None, 'p': 'pig'}
#判断k是否存在字典中
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print('a' in dic) #True
print('A' in dic) #False
源代码:
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)
"""
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass
#清空字典
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
dic.clear()
print(dic)
'''
{}
'''
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass
#浅拷贝,只拷贝第一层
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
#字典的拷贝,同列表的深浅拷贝
dic1 = dic.copy()
print(dic1)
print(id(dic),id(dic1))
dic['b'][0]='BANANA'
print(dic,dic1)
@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass
#Python 字典 fromkeys() 函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值。
seq = ('appale', 'banana', 'cat')
dic = dict.fromkeys(seq)
print(dic)
dic2 = dict.fromkeys(seq,10)
print(dic2)
'''
{'appale': None, 'banana': None, 'cat': None}
{'appale': 10, 'banana': 10, 'cat': 10}
'''
def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass
#通过key获得value,可以加参数,如果k不在d里面,输出d的值
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print(dic.get('b')) #['banana', 'bear']
print(dic.get('c','egg')) #cat
print(dic.get('e','egg')) #egg,'e'不在字典里,输出gg
def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print(dic.items())
'''
dict_items([('a', 'appale'), ('b', ['banana', 'bear']), ('c', 'cat'), ('d', 'dog')])
'''
###遍历输出键值对####
for k,v in dic.items():
print(k,v)
'''
a appale
b ['banana', 'bear']
c cat
d dog
'''
def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass
#获取所有keys
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print(dic.keys())
'''
dict_keys(['a', 'b', 'c', 'd'])
'''
####遍历keys####
for k in dic.keys():
print(k)
'''
a
b
c
d
'''
def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass
#根据key,删除value
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print(dic.pop('a')) #appale
print(dic) #{'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog'}
# print(dic.pop('e')) #KeyError
print(dic.pop('e','egg')) #egg
print(dic) #{'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog'}
def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass
#删除最后一对键值对
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print(dic.popitem())
print(dic)
'''
('d', 'dog')
{'a': 'appale', 'b': ['banana', 'bear'], 'c': 'cat'}
'''
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass
#向字典追加元素,键为k,值为d
dic = {}
dic.setdefault("k1")
print(dic)
dic.setdefault("k2", "111")
print(dic)
'''
{'k1': None}
{'k1': None, 'k2': '111'}
'''
def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass
#更新字典,如果k存在则替换,如果不存在则增加
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
dic1 = {'e':'egg','f':'fun'}
dic2 = {'a':'APPALE','p':'pig'}
dic.update(dic1)
print(dic)
dic.update(dic2)
print(dic)
'''
{'a': 'appale', 'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog', 'e': 'egg', 'f': 'fun'}
{'a': 'APPALE', 'b': ['banana', 'bear'], 'c': 'cat', 'd': 'dog', 'e': 'egg', 'f': 'fun', 'p': 'pig'}
'''
def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass
#获取所有values
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
print(dic.values())
'''
dict_values(['appale', ['banana', 'bear'], 'cat', 'dog'])
'''
字典的遍历:
#字典的遍历
dic = {'a':'appale','b':['banana','bear'],'c':'cat','d':'dog'}
#方法一(推荐该方法,速度快)
print("---方法一---")
for k in dic:
print(k,dic[k])
#方法二
print("---方法二---")
for (k,v) in dic.items():
print(k,v)
#方法三
print("---方法三---")
print(dic.items())
'''
---方法一---
a appale
b ['banana', 'bear']
c cat
d dog
---方法二---
a appale
b ['banana', 'bear']
c cat
d dog
---方法三---
dict_items([('a', 'appale'), ('b', ['banana', 'bear']), ('c', 'cat'), ('d', 'dog')])
'''
字典的排序:
字典和列表的排序可以使用sorted()实现。
dic = {'5':'zhangsan','p':'pig','a':'123','D':'dog'}
print(dic)
print(sorted(dic.items()))
#按照key排序
print(sorted(dic.items(),key=lambda d:d[0]))
#按照value排序
print(sorted(dic.items(),key=lambda d:d[1]))
'''
{'5': 'zhangsan', 'p': 'pig', 'a': '123', 'D': 'dog'}
[('5', 'zhangsan'), ('D', 'dog'), ('a', '123'), ('p', 'pig')]
[('5', 'zhangsan'), ('D', 'dog'), ('a', '123'), ('p', 'pig')]
[('a', '123'), ('D', 'dog'), ('p', 'pig'), ('5', 'zhangsan')]
'''
全局字典sys.modules模块
sys.modules是一个全局字典,这个字典是python启动后就加在在内存中的。每当导入新的模块,sys.modules都将记录这些模块。字典sys.modules对加载的模块起到了缓存作用。当某个模块第一次导入时,字典sys.modules将自动记录该模块。当第2次导入此模块时,python会直接到字典中查找,从而加快了程序运行的速度。
sys.modules具有字典的所有方法,可以通过该方法了解当前的环境加载了哪些模块。
import sys
print(sys.modules.keys()) #返回sys模块及python自动加载的模块
print(sys.modules.values()) #返回模块的引用
print(sys.modules["os"]) #返回os对应的引用
#实现对导入模块的过滤
import sys
d = sys.modules.copy()
print(d)
import copy,string
print(set(sys.modules) - set(d)) #{'_string', 'string', 'copy'}
4. 集合
集合是无序的,作用是:去重、关系测试。
集合常用操作:
l = [1,2,3,1,2,3]
#集合去重
l = set(l)
print(l)
print(type(l))
#集合长度
s = set('hello')
print(s) #{'h', 'e', 'o', 'l'}
print(len(s)) #4
#测试包含
print('h' in s)
#测试不包含
print('e' not in s)
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
#交集
print(s1.intersection(s2))
#{'b', 'a'}
#并集
print(s1.union(s2))
#{'b', 'd', 'e', 'c', 'a'}
#差集
print(s1.difference(s2)) #{'c'}
print(s2.difference(s1)) #{'d', 'e'}
#子集
print(s1.issubset(s2)) #False
print(set(['a','b']).issubset(s1)) #True
#父集
print(s1.issuperset(set(['a','b']))) #True
#对称差集
print(s1.symmetric_difference(s2)) #{'c', 'e', 'd'}
print(s2.symmetric_difference(s1)) #{'c', 'e', 'd'}
#isdisjoint如果没有交集返回真
print(s1.isdisjoint(s2)) #False
print(s1.isdisjoint(set([1,2,3]))) #True
关系测试的另一种写法:
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
#并集
print(s1 | s2)
#交集
print(s1 & s2)
#差集
print(s1 - s2)
#对称差集 (在前者中不在后者中)
print(s1 - s2) #{'c'}
print(s2 - s1) #{'e', 'd'}
源代码:
class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set.
This has no effect if the element is already present.
"""
pass
#新增一个元素
s = set(['a','b','c','d'])
s.add('e')
print(s)
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass
#清空集合
s = set(['a','b','c','d'])
s.clear()
print(s)
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass
#浅拷贝,同列表
s = set(['a','b','c','d'])
s1 = s.copy()
print(s1)
print(id(s),id(s1))
def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
"""
pass
#差集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.difference(s2)) #{'c'}
print(s2.difference(s1)) #{'d', 'e'}
def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. """
pass
#将所有元素删除,重新生成一个有差集的集合
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.difference(s2)) #{'c'}
s1.difference_update(s2)
print(s1) #{'c'}
def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
"""
pass
#删除指定元素,如果该元素不在集合中也不会报错
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
s1.discard('b')
print(s1)
#{'a', 'c'}
def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
"""
pass
#交集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.intersection(s2))
#{'b', 'a'}
def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another. """
pass
#更新列表为交集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.intersection(s2)) #{'a', 'b'}
s1.intersection_update(s2)
print(s1) #{'a', 'b'}
def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. """
pass
#如果没有交集返回真
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.isdisjoint(s2)) #False
print(s1.isdisjoint(set([1,2,3]))) #True
def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. """
pass
#子集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.issubset(s2)) #False
print(set(['a','b']).issubset(s1)) #True
def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. """
pass
#父集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.issuperset(set(['a','b']))) #True
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass
#随机删除一个元素,如果集合为空则报错
s1 = set(['a','b','c'])
print(s1.pop()) #默认随机删除
print(s1)
s2 = set()
print(s2.pop())
#KeyError: 'pop from an empty set'
def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
"""
pass
#删除指定元素,如果元素不在集合中则报错
s1 = set(['a','b','c'])
s1.remove('b')
print(s1) #{'c', 'a'}
s1.remove('d') #KeyError: 'd'
def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
"""
pass
#对称差集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.symmetric_difference(s2)) #{'c', 'e', 'd'}
print(s2.symmetric_difference(s1)) #{'c', 'e', 'd'}
def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. """
pass
#将集合的对称差集重新写到该集合中
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.symmetric_difference(s2)) #{'d', 'e', 'c'}
s1.symmetric_difference_update(s2)
print(s1) #{'c', 'e', 'd'}
def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
"""
pass
#并集
s1 = set(['a','b','c'])
s2 = set(['a','b','d','e'])
print(s1.union(s2))
#{'b', 'd', 'e', 'c', 'a'}
def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. """
pass
#添加多个元素
s1 = set(['a','b','c'])
s1.update('e')
s1.update('e','f',(1,2))
print(s1)
#{1, 2, 'b', 'f', 'e', 'a', 'c'}