(二)1月21日直播视频

python :GLI? 会变慢

python的种类:

Cpython:c解释器,编译阶段解释成.pyc字节码,执行的时候需要先转换为机器码,再cpu运行

Jython:java解释器,解释为java字节码,机器码,cpu

ironpython:c#解释器,c#字节码,机器码,cpu

rubypython、jspyhon等一样

pypy:解释器,(编译阶段字:节码,直接机器码),执行的时候就是机器码了

我们所说的一般指Cpython.

对于我们来讲,写的代码是一样的,不过用的解释器不同而已

编码:

python3已经不用加 # -*- coding:utf-8 -*-这样一行了,所有都自动转换为utf-8

ascii码:8位

unicode(万国码):至少16位

utf-8:可变长码(类似霍夫曼编码的感觉)

gbk:和utf-8是一个类



index.py

import sys

print(sys.argv) # 感觉这个函数类似收集的作用,将输入参数收集成list


terminal: python3 index.py run

>>['index.py', 'run']


缓冲池的概念:

小数字池:内部维持一个内存取,保存-5-257,作用是重复定义5的时候,可以共用5这个数字

小字符串池:也是类似,不用重复开辟空间字符串

甚至其他列表等等也有。

int类型

在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

In [22]: 9223372036854775808


Out[22]: 9223372036854775808L




In [23]: 9223372036854775807


Out[23]: 9223372036854775807


移除空白:strip

分割:split

长度 len(obj)

索引 obj[i]

切片::

循环:for, while, (js:foreach)

         break, continue, pass(占位符,不会跳过), return, exit(退出整个程序)

删除:del remove pop

包含:in,__contains__

t1 = (11, 22, {'k1': 'v1'})
# t1[2] = {'x': 5} # tuple的元素不可以被修改
t1[2]['k2'] = 5 # tuple的元素的元素可以被修改
print(t1)

字典:

删除:del[key]

新增:d[key] = ...

键、值、键值对

    keys(), values(), items() 


登陆作业讲解:

事先存在一个加锁文件,一个用户名和密码文件。

下面简单介绍一下for-else while-else组合

循环组合中的else执行的情况下是循环正常结束(即不是使用break退出)

代码:



 
 
  1. numbers = [1,2,3,4,5]
  2. for n in numbers:
  3.    if (n > 5):
  4.        print('the value is %d '%(n))
  5.        break
  6. else:
  7.    print('the for loop does not end with break')
  8.  
  9. i = 0
  10. while(numbers[i] < 5):
  11.    print('the index %d value is %d'%(i, numbers[i]))
  12.    if (numbers[i] < 0) :
  13.        break
  14.    i = i + 1
  15. else:
  16.    print('the loop does not end with break')
  17. numbers = [1,2,3,4,5]
  18. for n in numbers:
  19.    if (n > 5):
  20.        print('the value is %d '%(n))
  21.        break
  22. else:
  23.    print('the for loop does not end with break')
  24.  
  25. i = 0
  26. while(numbers[i] < 5):
  27.    print('the index %d value is %d'%(i, numbers[i]))
  28.    if (numbers[i] > 3) :
  29.        break
  30.    i = i + 1
  31. else:
  32.    print('the loop does not end with break')

输出:



 
 
  1. the for loop does not end with break
  2. the index 0 value is 1
  3. the index 1 value is 2
  4. the index 2 value is 3
  5. the index 3 value is 4
  6. the loop does not end with break
  7. the for loop does not end with break
  8. the index 0 value is 1
  9. the index 1 value is 2
  10. the index 2 value is 3
  11. the index 3 value is 4

with open() as f:

    ...


1.py      __name__ = '1.py'

2.py      __name__ = '2.py'

lib/3.py      __name__ = 'lib.3'

index.py      __name__ = '__main__'

执行

python index.py 


对于python,一切事物都是对象,对象是由类创建的。对象所有的功能都在它所属于的类里面。






In [5]: import time


In [7]: print(type(time))

<type 'module'>


In [8]: print(type(time.time))

<type 'builtin_function_or_method'>


Python 2.7.6 (default, Sep  9 2014, 15:04:36) 


[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin


Type "help", "copyright", "credits" or "license" for more information.


>>> import twisted


>>> from twisted.internet import reactor


>>> print(type(reactor))


<class 'twisted.internet.selectreactor.SelectReactor'>

用type可以看到reactor这个对象的类在哪里哟。


int型:

In [1]: age = 18

In [2]: age.bit_length()

Out[2]: 5


x=-10

x.__abs__()与abs(x)相同

内置函数abs(x)会调用x.__abs__()


语法糖:

x.__add__(y)与x+y相同

x.__eq__(y) <==> x==y

x.__floordiv__(y) <==> x//y

内置函数:

x.__divmod__(y) <==> divmod(x, y)


float型:

x  = 10.9

x.as_integer_ratio():转成分数形式

x.as_integer_ratio()

看源代码:command + 鼠标左击即可,而得到的源代码如果看不到,说明是用c实现的,其实也可以看到,貌似房子Scripts目录下面


字符串:

dir(name)可以看到类里面的所有成员(不仅包括方法,还包括属性和成员)

x.__contains__(y) <==> y in x

__getattribute__ :反射时用到,以后会教

__getitem__():x.__getitem__(y) <==> x[y]语法糖,s[i]


In [79]: name = 'eric'

In [80]: name.capitalize()

Out[80]: 'Eric'



In [84]: name.center(10, '-')

Out[84]: '---eric---'



In [87]: name = 'fadfdsafdsafdsa'

In [88]: name.count('a')

Out[88]: 4

在python3里面,只有encode

比如:name = '了解'

result = name.encode('gbk')


print(name)

内部执行了utf-8=>unicode=>gbk的过程

S.endswith(suffix[, start[, end]]) -> bool



S.expandtabs([tabsize]) -> string

Return a copy of S where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.



字符串格式化


In [116]: name = "alex {0} as {1}"

In [117]: name.format('sb', 'niubi')

Out[117]: 'alex sb as niubi'



In [118]: name = 'xx {s1} as {s2}'

In [119]: name.format(s1='1', s2='2')

Out[119]: 'xx 1 as 2'


name.isalnum()等is开头的判断方法


3.x中


  >>> map = str.maketrans('123','abc', '78')#要删除的字符需要在这指定
  >>> s = '54321123789'
  >>> s.translate(map)
  '54cbaabc9'



In [126]: name = 'alexissbissb'


In [128]: name.partition('is')

Out[128]: ('alex', 'is', 'sbissb')




In [136]: name = 'alex'

In [137]: name.rjust(10,'x')

Out[137]: 'xxxxxxalex'




上下文管理:

with open('log.txt', 'r') as:

    f.write(...)

原理:


import contextlib

@contextlib.contextmanager

def show():

    print('123')

    yield

    print('456')


with show():

    print('999')

输出

123

999

456


列表:

建议使用,做结尾,这样可以防止看不清楚括号的数目,元组和字典也在结尾加逗号。

li = [1,2,3,]

li.extend([1,3,4,])


字典:

# dic = {'x':'v1', 'y':'v2'} 两者等价
dic = dict(x='v1', y='v2',)
print(dic)
>> {'y': 'v2', 'x': 'v1'}


dict.from_keys([1,2,],'x') 

>>{1: 'x', 2: 'x'}


下面的显示是封装到对象里了,暂时不用管

In [20]: print(dic)

{'y': 'v2', 'x': 'v1'}


In [21]: print(dic.items())

dict_items([('y', 'v2'), ('x', 'v1')])


In [22]: print(dic.keys())

dict_keys(['y', 'x'])


In [23]: print(dic.values())

dict_values(['v2', 'v1'])


In [32]: dic

Out[32]: {'x': '4', 'y': '4'}

In [33]: dic.pop('y')

Out[33]: '4'

In [36]: dic

Out[36]: {'x': '4'}


dic.setdefault() # 我已会了


In [51]: dic

Out[51]: {3: None, 4: 'y', 'x': 'yangkai'}

In [52]: dic.update({3:'u', 'z':6})

In [53]: dic

Out[53]: {'z': 6, 3: 'u', 4: 'y', 'x': 'yangkai'}


 
 
  1. # -*- coding:utf-8 -*-
  2. # 练习:元素分类
  3. # 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66
  4. # 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
  5. # 即: {'k1': 大于66 , 'k2': 小于66}
  6. dic = {}
  7. all_list = [11, 22, 33, 44, 55, 66, 77, 88, 99, ]
  8. for i in all_list:
  9.    if i > 66:
  10.        if 'k1' in dic:
  11.            dic['k1'].append(i)
  12.        else:
  13.            dic['k1'] = [i, ]
  14.    else:
  15.        if 'k2' in dic:
  16.            dic['k2'].append(i)
  17.        else:
  18.            dic['k2'] = [i, ]
  19. print(dic)

作业:

1、博客

2、购物车

    商品展示,价格

    买,加入购物车

    付款,钱不够,

 3、预习:

    set:练习

练习:寻找差异
# 数据库中原有
old_dict  =  {
     "#1" :{  'hostname' :c1,  'cpu_count' 2 'mem_capicity' 80  },
     "#2" :{  'hostname' :c1,  'cpu_count' 2 'mem_capicity' 80  }
     "#3" :{  'hostname' :c1,  'cpu_count' 2 'mem_capicity' 80  }
}
 
# cmdb 新汇报的数据
new_dict  =  {
     "#1" :{  'hostname' :c1,  'cpu_count' 2 'mem_capicity' 800  },
     "#3" :{  'hostname' :c1,  'cpu_count' 2 'mem_capicity' 80  }
     "#4" :{  'hostname' :c2,  'cpu_count' 2 'mem_capicity' 80  }
}
 
需要删除:?
需要新建:?
需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新


 
 
  1. # -*- coding:utf-8 -*-
  2. # 练习:寻找差异
  3. # 数据库中原有
  4. c1 = 'yangkai'
  5. c2 = 'Tom'
  6. old_dict = {
  7.    "#1": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80},
  8.    "#2": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80},
  9.    "#3": {'hostname': c1, 'cpu_count': 2, 'mem_capicity': 80},
  10. }
  11. # cmdb 新汇报的数据
  12. new_dict = {
  13.    "#1": {'hostname': c2, 'cpu_count': 2, 'mem_capicity': 800},
  14.    "#3": {'hostname': c2, 'cpu_count': 2, 'mem_capicity': 80},
  15.    "#4": {'hostname': c2, 'cpu_count': 2, 'mem_capicity': 80},
  16. }
  17. # 需要删除:?
  18. # 需要新建:?
  19. # 需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
  20. oldKeysSet = set(list(old_dict.keys()))
  21. newKeysSet = set(list(new_dict.keys()))
  22. delete = oldKeysSet - newKeysSet
  23. print(delete)
  24. for key in delete:
  25.    old_dict.pop(key)
  26. create = newKeysSet - oldKeysSet
  27. print(create)
  28. for key in create:
  29.    old_dict.setdefault(key, new_dict[key])
  30. update = oldKeysSet & newKeysSet
  31. print(update)
  32. for key in update:
  33.    old_dict[key] = new_dict[key]
  34. print(old_dict)

   collections

    文件操作


深浅拷贝,一看就懂

a = b[:]是浅拷贝,import copy,copy.deepcopy()是神拷贝

 
 
  1. In [1]: a = [1,2,[3,4]]
  2. In [2]: b=a[:]
  3. In [3]: b
  4. Out[3]: [1, 2, [3, 4]]
  5. In [4]: b[2][0]=12
  6. In [5]:  b
  7. Out[5]: [1, 2, [12, 4]]
  8. In [6]: a
  9. Out[6]: [1, 2, [12, 4]]
  10. In [7]: id(a)
  11. Out[7]: 4513710344
  12. In [8]: id(b)
  13. Out[8]: 4494952008
  14. In [9]: id(a[0])
  15. Out[9]: 4488910864
  16. In [10]: id(b[0])
  17. Out[10]: 4488910864
  18. In [11]: a
  19. Out[11]: [1, 2, [12, 4]]
  20. In [12]: a[0]=11
  21. In [13]: a
  22. Out[13]: [11, 2, [12, 4]]
  23. In [14]: b
  24. Out[14]: [1, 2, [12, 4]]

python3里面,dic.items(),keys(),values()返回的是迭代器,list(dic.items())可以转化为list对象

迭代器可以for x in dic.items()这么用

字典的三种构造方式:

  
  
  1. 1
  2. a=dict
  3. a={'alex':30,'tenglan':23}
  4. a['alex']------取出30,一种映射关系
  5. 2
  6. >>> items=[('name','alex')]
  7. >>> dict(items)
  8. {'name': 'alex'}
  9. >>> d=dict([('name','yuan'),('job','stu')])
  10. >>> d = {k:v for (k,v) in zip(['a','b','c'],[1,2,3])}
  11. >>> d
  12. {'a': 1, 'c': 3, 'b': 2}

 字典的深浅拷贝,与列表类似咯:

 
 
  1. In [85]: a
  2. Out[85]: {'job': [1, 2, 3, 5, 6, 5], 'name': 'alex'}
  3. In [86]: b = copy.copy(a)
  4. In [87]: c = copy.deepcopy(a)
  5. In [88]: id(a['job'])
  6. Out[88]: 4513713288
  7. In [89]: id(b['job'])
  8. Out[89]: 4513713288
  9. In [90]: id(c['job'])
  10. Out[90]: 4514397768

格式化输出

 
 
  1. In [145]: a
  2. Out[145]: {'age': '33', 'name': 'alxe', 'wang': '1234', 'xx': 5, 'zhang': '56778'}
  3. In [146]: "wang's phone number is  %(wang)s %(xx)s" %a
  4. Out[146]: "wang's phone number is  1234 5"
  5. In [147]: "wang's phone number is  %(wang)s %(xx)d" %a
  6. Out[147]: "wang's phone number is  1234 5"

if语句:空字符串会很方便

 
 
  1. In [151]: bool([])
  2. Out[151]: False
  3. In [152]: bool([1])
  4. Out[152]: True
  5. In [153]: if []: # False
  6.              print('ok')

for else循环:

格式: for 元素变量 in 可迭代对象

example:

for i in [1,2,3,'alex']:

    print(i)

if else的类三元运算符:

 
 
  1. In [153]: print('ok') if 3>1 else print('not ok')
  2. ok
  3. In [154]: print('ok') if 3<1 else print('not ok')
  4. not ok
 
 
  1. In [156]: 'ok' if 3<1 else 'not ok'
  2. Out[156]: 'not ok'
  3. In [157]: 'ok' if 3>1 else 'not ok'
  4. Out[157]: 'ok'
 
 
  1. In [160]: a = 1 if 3<5 else 4
  2. In [161]: a
  3. Out[161]: 1
  4. In [162]: a = 1 if 3>5 else 4
  5. In [163]: a
  6. Out[163]: 4

字典的妙用,不用再去用循环实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值