(三)1月28日视频

sys模块

    今后要查python解释器的信息可以去sys里面找

set

    关于set内元素的要求(http://stackoverflow.com/questions/1306631/python-add-list-to-set):

    You can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.

    You can however add tuples to the set, because you cannot change the contents of a tuple:

a.add(('f', 'g'))
print(a)
>>>set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])

    Edit: some explanation: The documentation defines a set as an unordered collection of distinct hashable objects. The objects have to be hashable so that finding, adding and removing elements can be done faster than looking at each individual element every time you perform these operations. The specific algorithms used are explained in the Wikipedia article. Pythons hashing algorithms are explained on effbot.org and pythons __hash__ function in the python reference.

Some facts:

  • Set elements as well as dictionary keys have to be hashable
  • Some unhashable datatypes:
    • list: use tuple instead
    • set: use frozenset instead
    • dict: has no official counterpart, but there are some recipes
  • Object instances are hashable by default with each instance having a unique hash. You can override this behavior as explained in the python reference.
    有关set的代码:
# -*- coding:utf-8 -*-

# 集合,作用之一是可以再做爬虫的时候保存已访问过的网址
# 访问速度快,天生解决了重复问题
s1 = set()
s1.add('alex')
print(s1)
s1.add('alex')

print(s1)
s2 = set(['alex', 'yangkai', 'alex'])
print(s2)

s3 = s2.difference(s1)
print(s2)
print(s3)

# s4 = s2.difference_update(s1)
# print(s2)
# print(s4)

s2.remove('alex')  # 不存在会抛异常
print(s2)

print(s2.pop())
print(s2)

s2.discard('alex')  # 不存在也不会抛异常
print(s2)

s1 = set([11,22,33])
s2 = set([22, 44])
print(s1.difference(s2))  # 差集
print(s1.symmetric_difference(s2))  # 两个集合的对称差是只属于其中一个集合,而不属于另一个集合的元素组成的集合
print(s2.symmetric_difference(s1))  # 显然与上一行的结果相同
输出:
{'alex'}
{'alex'}
{'alex', 'yangkai'}
{'alex', 'yangkai'}
{'yangkai'}
{'yangkai'}
yangkai
set()
set()
{33, 11}
{33, 11, 44}
{33, 11, 44}

lambda表达式

# lambda表达式,简单函数的表示方式
func = lambda a: a+1
# 创建了形式参数
# 创建了函数体,并且把结果return

print(func(99))

发送邮件的函数

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

def mail(user):
    ret = True
    try:
        msg = MIMEText('你好,这是实验,我试试看的', 'plain', 'utf-8')
        msg['From'] = formataddr(["杨恺",'yk_ecust_2007@163.com'])
        msg['To'] = formataddr(["赵老板", user])
        msg['Subject'] = "实验"

        server = smtplib.SMTP("smtp.163.com", 25)
        server.login("yk_ecust_2007@163.com", "xxxx")
        # for i in range(5):
        server.sendmail('yk_ecust_2007@163.com', [user,], msg.as_string())
        server.quit()
    except Exception as e:
        print(e)
        ret = False
    return ret
count = 0
for i in range(5000):
    ret = mail('630915171@qq.com')
    if ret:
        count += 1
        print('发送成功', count)
    else:
        print('发送失败')

函数的动态参数

理解收集和分散就可以了

# 动态参数
def show1(*args):  # 收集,将参数转换为元组
    print(args, type(args))

n = [1, 2, 3, 4]
show1(n, 1, 2, 3)

def show2(**kwargs):  # 收集,将参数转换为字典
    print(kwargs, type(kwargs))

show2(n1=78, n2='xx')


def show3(*args, **kwargs):
    print(args, type(args))
    print(kwargs, type(kwargs))

show3(11,22,'xx',33,{1:'z'},x=4,y=8)

l = [11, 22, 33, 44]
d = {'x':1, 'y':2, 'z':3}
show3(l, d)

def show(k1, k2):
    print(k1, k2)

show(*[11,22])  # 分散

show(**{'k1':5, 'k2':6})  # 分散

show3(*l, **d)  # 先分散,再收集

# 应用
print('应用'.center(50, '-'))
s1 = "{0} is {1}"
print(s1.format('alex', '2b'))

l = ['alex', '2b']
print(s1.format(*l))

s2 = "{name} is {actor}"
print(s2.format(name = 'alex', actor = 'sb'))

d = {'name':'alex', 'actor':'sb'}
print(s2.format(**d))

输出
([1, 2, 3, 4], 1, 2, 3) <class 'tuple'>
{'n1': 78, 'n2': 'xx'} <class 'dict'>
(11, 22, 'xx', 33, {1: 'z'}) <class 'tuple'>
{'y': 8, 'x': 4} <class 'dict'>
([11, 22, 33, 44], {'y': 2, 'x': 1, 'z': 3}) <class 'tuple'>
{} <class 'dict'>
11 22
5 6
(11, 22, 33, 44) <class 'tuple'>
{'y': 2, 'x': 1, 'z': 3} <class 'dict'>
------------------------应用------------------------
alex is 2b
alex is 2b
alex is sb
alex is sb

深浅拷贝

字符串和数字,有数字池和字符串池,所以一般来讲相同的字符串或数字,所在内存是同一个

赋值:见下图

浅拷贝:只拷贝第一层,见下图

深拷贝:递归得拷贝所有内容

# -*- coding:utf-8 -*-
import copy
# 浅拷贝
# copy.copy()
# # 深拷贝
# copy.deepcopy()
# 赋值
# =

# 字符串和数字,数字池和字符池,可以认为是内存中的最小单元
print('字符串和数字,数字池和字符池'.center(50, '-'))
a1 = 123123
a2 = 123123
print(id(a1))
print(id(a2))
a2 = a1
print(id(a1))
print(id(a2))


a3 = copy.copy(a1)
print(id(a1))
print(id(a3))

a4 = copy.deepcopy(a1)
print(id(a1))
print(id(a4))

# 其他,元组\列表\字典等
print('其他,元组\列表\字典等'.center(50, '-'))
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
n2 = n1
print(id(n1))
print(id(n2))

print('浅拷贝'.center(30, '-'))
n3 = copy.copy(n1)
print(id(n1))
print(id(n3))
print(id(n1['k3']))
print(id(n3['k3']))

print('深拷贝'.center(30, '-'))
n4 = copy.deepcopy(n1)
print(id(n1))
print(id(n4))
print(id(n1['k3']))
print(id(n4['k3']))
print(id(n1['k1']))
print(id(n4['k1']))

# 应用
print('应用'.center(50, '-'))
dic = {
    'cpu': [80, ],
    'mem': [80, ],
    'disk': [80, ],
}

# new_dic = copy.copy(dic)
# new_dic['cpu'][0] = 50
# print('dic', dic)
# print('new_dic', new_dic)

new_dic = copy.deepcopy(dic)
new_dic['cpu'][0] = 50
print('dic', dic)
print('new_dic', new_dic)


输出
------------------字符串和数字,数字池和字符池------------------
4413742512
4413742512
4413742512
4413742512
4413742512
4413742512
4413742512
4413742512
-------------------其他,元组\列表\字典等-------------------
4413749064
4413749064
-------------浅拷贝--------------
4413749064
4414626952
4415069064
4415069064
-------------深拷贝--------------
4413749064
4414597064
4415069064
4415067336
4414577944
4414577944
------------------------应用------------------------
dic {'mem': [80], 'disk': [80], 'cpu': [80]}
new_dic {'mem': [80], 'disk': [80], 'cpu': [50]}

collections

很大一部分见之前的博客:点击打开链接

另外新增的代码:

# -*- coding:utf-8 -*-
import collections
obj = collections.Counter('akjfadskjkjkjjkj')
print(obj)
print(obj.most_common(4))

for item in obj.elements():
    print(item)

for k, v in obj.items():
    print(k, v)

obj2 = collections.Counter(['11', '22', '33', '22'])
obj2.update(['laex', '11', '11'])
print(obj2)
obj2.subtract(['laex', '11', '11', '11', '11'])
print(obj2)


# Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
prime_factors = collections.Counter({2: 2, 3: 3, 17: 1})
product = 1
for factor in prime_factors.elements():     # loop over factors
    product *= factor
print(product)

# 有序字典
dic = collections.OrderedDict()
# dic = dict()
dic['key1'] = 'v1'
dic['key2'] = 'v2'
dic['key3'] = 'v3'
# dic.move_to_end('key2')
print(dic)
print(dic.popitem())  # 后进先出
print(dic)
print(dic.pop('key2'))
print(dic)
dic.update({'key1':'v111', 'key10': 'v10'})
print(dic)

# 默认字典
dic = collections.defaultdict(list)
dic['k1'].append('alex')
dic['k1'].append(4)
dic['k2'].append('yangkai')
print(dic)

# 创建类
MytupleClass = collections.namedtuple('MytupleClass', ['x', 'y', 'z'])  # nametuple是个方法,创建了一个类MytupleClass
print(help(MytupleClass))  # 可以查看类MytupleClass的所有方法
obj = MytupleClass(11, 22, 33)
print(obj.x)
print(obj.y)
print(obj.z)
print(obj._asdict())

# 双向队列,内存级别
d = collections.deque()
d.append(1)
d.appendleft(10)
d.appendleft(1)
print(d)
print(d.count(1))
d.extend(['yy', 'uu', 'zz'])
d.extendleft(['yy1', 'uu1', 'zz1'])
print(d)
d.rotate(1)
print(d)

# 单向队列,以后能用于多线程,学网络通信的时候也会用到
import queue
q = queue.Queue()
q.put('123')
q.put('678')
print(q.qsize())
print(q.get())
输出:

# -*- coding:utf-8 -*-
import collections
obj = collections.Counter('akjfadskjkjkjjkj')
print(obj)
print(obj.most_common(4))

for item in obj.elements():
    print(item)

for k, v in obj.items():
    print(k, v)

obj2 = collections.Counter(['11', '22', '33', '22'])
obj2.update(['laex', '11', '11'])
print(obj2)
obj2.subtract(['laex', '11', '11', '11', '11'])
print(obj2)


# Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
prime_factors = collections.Counter({2: 2, 3: 3, 17: 1})
product = 1
for factor in prime_factors.elements():     # loop over factors
    product *= factor
print(product)

# 有序字典
<span style="font-family: 'Helvetica Neue'; font-size: 15px; line-height: 24px;"># 显然可以用字典和列表共同实现有序字典,确实也是这么实现的</span>
dic = collections.OrderedDict()
# dic = dict()
dic['key1'] = 'v1'
dic['key2'] = 'v2'
dic['key3'] = 'v3'
# dic.move_to_end('key2')
print(dic)
print(dic.popitem())  # 后进先出
print(dic)
print(dic.pop('key2'))
print(dic)
dic.update({'key1':'v111', 'key10': 'v10'})
print(dic)

# 默认字典
dic = collections.defaultdict(list)
dic['k1'].append('alex')
dic['k1'].append(4)
dic['k2'].append('yangkai')
print(dic)

# 创建类
MytupleClass = collections.namedtuple('MytupleClass', ['x', 'y', 'z'])  # nametuple是个方法,创建了一个类MytupleClass
# print(help(MytupleClass))  # 可以查看类MytupleClass的所有方法
obj = MytupleClass(11, 22, 33)
print(obj.x)
print(obj.y)
print(obj.z)
print(obj._asdict())

# 双向队列,内存级别
d = collections.deque()
d.append(1)
d.appendleft(10)
d.appendleft(1)
print(d)
print(d.count(1))
d.extend(['yy', 'uu', 'zz'])
d.extendleft(['yy1', 'uu1', 'zz1'])
print(d)
d.rotate(1)
print(d)

# 单向队列,以后能用于多线程,学网络通信的时候也会用到
import queue
q = queue.Queue()
q.put('123')
q.put('678')
print(q.qsize())
print(q.get())# 
输出:

<span style="font-size:18px;">Counter({'j': 6, 'k': 5, 'a': 2, 'd': 1, 's': 1, 'f': 1})
[('j', 6), ('k', 5), ('a', 2), ('d', 1)]
d
s
j
j
j
j
j
j
k
k
k
k
k
a
a
f
d 1
s 1
j 6
k 5
a 2
f 1
Counter({'11': 3, '22': 2, 'laex': 1, '33': 1})
Counter({'22': 2, '33': 1, 'laex': 0, '11': -1})
1836
OrderedDict([('key1', 'v1'), ('key2', 'v2'), ('key3', 'v3')])
('key3', 'v3')
OrderedDict([('key1', 'v1'), ('key2', 'v2')])
v2
OrderedDict([('key1', 'v1')])
OrderedDict([('key1', 'v111'), ('key10', 'v10')])
defaultdict(<class 'list'>, {'k1': ['alex', 4], 'k2': ['yangkai']})
11
22
33
OrderedDict([('x', 11), ('y', 22), ('z', 33)])
deque([1, 10, 1])
2
deque(['zz1', 'uu1', 'yy1', 1, 10, 1, 'yy', 'uu', 'zz'])
deque(['zz', 'zz1', 'uu1', 'yy1', 1, 10, 1, 'yy', 'uu'])
2
123</span>

内置函数

# -*- coding:utf-8 -*-

# 内置函数不需要导入模块就可以使用


print(all([1,2,'']))
print(any([1,'',None]))


class Foo:

    def __repr__(self):
        return 'adfafsfas'

f = Foo()
# print(f.__repr__())
print(ascii(f))

print(bytearray('阿扎', encoding='utf-8'))
print(bytes('阿扎', encoding='utf-8'))

func = lambda a: a+1
print(callable(func))  # 是否可被调用,即func()可以被执行
l = []
print(callable(l))  # 如果类里面实现了__call__,那么就为真
print(chr(99))
print(ord('A'))
import random
print(chr(random.randint(30,130)))
# 当你给dir()提供一个模块名字时,它返回在那个模块中定义的名字的列表。当没有为其提供参数时, 它返回当前模块中定义的名字的列表。
print(dir())

print(eval('6*8'))

l = [1,2,3,4]
print(list(map(lambda a:a+100, l)))
def func(x):
    return x*50
print(list(map(func, l)))

def func2(x):
    return x >= 3

print(list(filter(func2, l)))

print(hash('afsdjfa;jfjdfjfjkfsjkjljkjkljjkjklladjklf'))

另外几个内置函数

globals(),locals()

globals(), locals()

x = 1


def test(y):
    z = 1
    x = 3
    print(locals())
    print(globals())

test(5)

print(globals())
print(locals())
输出

{'y': 5, 'x': 3, 'z': 1}
{'__builtins__': <module '__builtin__' (built-in)>, '__file__': '/Users/ThomasYoung/Desktop/test.py', '__package__': None, 'x': 1, 'test': <function test at 0x10ebe3de8>, '__name__': '__main__', '__doc__': None}
{'__builtins__': <module '__builtin__' (built-in)>, '__file__': '/Users/ThomasYoung/Desktop/test.py', '__package__': None, 'x': 1, 'test': <function test at 0x10ebe3de8>, '__name__': '__main__', '__doc__': None}
{'__builtins__': <module '__builtin__' (built-in)>, '__file__': '/Users/ThomasYoung/Desktop/test.py', '__package__': None, 'x': 1, 'test': <function test at 0x10ebe3de8>, '__name__': '__main__', '__doc__': None}

repr(), ascii()都会调用类的__repr__()方法

vars()

vars( [object]) 
如果没有参数,根据现在的local符号表返回一个字典。如果是一个模块,类或类的实例对象作为参数(或其它任何有__dict__属性),根据对象的符号表返回一个字典。返回的字典不应被被修改:在相应符号表上的影响是未定义的。 

print(vars(list))
# 输出为:
{'__getslice__': <slot wrapper '__getslice__' of 'list' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, 'pop': <method 'pop' of 'list' objects>, 'remove': <method 'remove' of 'list' objects>, '__rmul__': <slot wrapper '__rmul__' of 'list' objects>, '__lt__': <slot wrapper '__lt__' of 'list' objects>, '__sizeof__': <method '__sizeof__' of 'list' objects>, '__init__': <slot wrapper '__init__' of 'list' objects>, 'count': <method 'count' of 'list' objects>, 'index': <method 'index' of 'list' objects>, '__delslice__': <slot wrapper '__delslice__' of 'list' objects>, '__new__': <built-in method __new__ of type object at 0x10b50fd10>, '__contains__': <slot wrapper '__contains__' of 'list' objects>, 'append': <method 'append' of 'list' objects>, '__doc__': "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items", '__len__': <slot wrapper '__len__' of 'list' objects>, '__mul__': <slot wrapper '__mul__' of 'list' objects>, 'sort': <method 'sort' of 'list' objects>, '__ne__': <slot wrapper '__ne__' of 'list' objects>, '__getitem__': <method '__getitem__' of 'list' objects>, 'insert': <method 'insert' of 'list' objects>, '__setitem__': <slot wrapper '__setitem__' of 'list' objects>, '__add__': <slot wrapper '__add__' of 'list' objects>, '__gt__': <slot wrapper '__gt__' of 'list' objects>, '__eq__': <slot wrapper '__eq__' of 'list' objects>, 'reverse': <method 'reverse' of 'list' objects>, 'extend': <method 'extend' of 'list' objects>, '__delitem__': <slot wrapper '__delitem__' of 'list' objects>, '__reversed__': <method '__reversed__' of 'list' objects>, '__imul__': <slot wrapper '__imul__' of 'list' objects>, '__setslice__': <slot wrapper '__setslice__' of 'list' objects>, '__iter__': <slot wrapper '__iter__' of 'list' objects>, '__iadd__': <slot wrapper '__iadd__' of 'list' objects>, '__le__': <slot wrapper '__le__' of 'list' objects>, '__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__ge__': <slot wrapper '__ge__' of 'list' objects>}


作业:

json模块

import json
inp_str = "[11,22,33,44]"
inp_list = json.loads(inp_str) # 根据字符串书写格式,将字符串自动转换成 列表类型
  
  
inp_str = ' {"k1":123, "k2": "wupeiqi"} '  # 正确的输入      切记,内部必须是 双引号 !!!
#inp_str = " {'k1':123, 'k2': 'wupeiqi'}"   # 错误的输入
inp_dict = json.loads(inp_str) # 根据字符串书写格式,将字符串自动转换成 字典类型




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值