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退出)
代码:
numbers = [1,2,3,4,5]
for n in numbers:
if (n > 5):
print('the value is %d '%(n))
break
else:
print('the for loop does not end with break')
i = 0
while(numbers[i] < 5):
print('the index %d value is %d'%(i, numbers[i]))
if (numbers[i] < 0) :
break
i = i + 1
else:
print('the loop does not end with break')
numbers = [1,2,3,4,5]
for n in numbers:
if (n > 5):
print('the value is %d '%(n))
break
else:
print('the for loop does not end with break')
i = 0
while(numbers[i] < 5):
print('the index %d value is %d'%(i, numbers[i]))
if (numbers[i] > 3) :
break
i = i + 1
else:
print('the loop does not end with break')
输出:
the for loop does not end with break
the index 0 value is 1
the index 1 value is 2
the index 2 value is 3
the index 3 value is 4
the loop does not end with break
the for loop does not end with break
the index 0 value is 1
the index 1 value is 2
the index 2 value is 3
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'}
# -*- coding:utf-8 -*-
# 练习:元素分类
# 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66
# 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
# 即: {'k1': 大于66 , 'k2': 小于66}
dic = {}
all_list = [11, 22, 33, 44, 55, 66, 77, 88, 99, ]
for i in all_list:
if i > 66:
if 'k1' in dic:
dic['k1'].append(i)
else:
dic['k1'] = [i, ]
else:
if 'k2' in dic:
dic['k2'].append(i)
else:
dic['k2'] = [i, ]
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
}
}
需要删除:?
需要新建:?
需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
|
# -*- coding:utf-8 -*-
# 练习:寻找差异
# 数据库中原有
c1 = 'yangkai'
c2 = 'Tom'
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': c2, 'cpu_count': 2, 'mem_capicity': 800},
"#3": {'hostname': c2, 'cpu_count': 2, 'mem_capicity': 80},
"#4": {'hostname': c2, 'cpu_count': 2, 'mem_capicity': 80},
}
# 需要删除:?
# 需要新建:?
# 需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
oldKeysSet = set(list(old_dict.keys()))
newKeysSet = set(list(new_dict.keys()))
delete = oldKeysSet - newKeysSet
print(delete)
for key in delete:
old_dict.pop(key)
create = newKeysSet - oldKeysSet
print(create)
for key in create:
old_dict.setdefault(key, new_dict[key])
update = oldKeysSet & newKeysSet
print(update)
for key in update:
old_dict[key] = new_dict[key]
print(old_dict)
collections
文件操作
深浅拷贝,一看就懂
a = b[:]是浅拷贝,import copy,copy.deepcopy()是神拷贝
In [1]: a = [1,2,[3,4]]
In [2]: b=a[:]
In [3]: b
Out[3]: [1, 2, [3, 4]]
In [4]: b[2][0]=12
In [5]: b
Out[5]: [1, 2, [12, 4]]
In [6]: a
Out[6]: [1, 2, [12, 4]]
In [7]: id(a)
Out[7]: 4513710344
In [8]: id(b)
Out[8]: 4494952008
In [9]: id(a[0])
Out[9]: 4488910864
In [10]: id(b[0])
Out[10]: 4488910864
In [11]: a
Out[11]: [1, 2, [12, 4]]
In [12]: a[0]=11
In [13]: a
Out[13]: [11, 2, [12, 4]]
In [14]: b
Out[14]: [1, 2, [12, 4]]
python3里面,dic.items(),keys(),values()返回的是迭代器,list(dic.items())可以转化为list对象
迭代器可以for x in dic.items()这么用
字典的三种构造方式:
1
a=dict
a={'alex':30,'tenglan':23}
a['alex']------取出30,一种映射关系
2
>>> items=[('name','alex')]
>>> dict(items)
{'name': 'alex'}
>>> d=dict([('name','yuan'),('job','stu')])
>>> d = {k:v for (k,v) in zip(['a','b','c'],[1,2,3])}
>>> d
{'a': 1, 'c': 3, 'b': 2}
字典的深浅拷贝,与列表类似咯:
In [85]: a
Out[85]: {'job': [1, 2, 3, 5, 6, 5], 'name': 'alex'}
In [86]: b = copy.copy(a)
In [87]: c = copy.deepcopy(a)
In [88]: id(a['job'])
Out[88]: 4513713288
In [89]: id(b['job'])
Out[89]: 4513713288
In [90]: id(c['job'])
Out[90]: 4514397768
格式化输出
In [145]: a
Out[145]: {'age': '33', 'name': 'alxe', 'wang': '1234', 'xx': 5, 'zhang': '56778'}
In [146]: "wang's phone number is %(wang)s %(xx)s" %a
Out[146]: "wang's phone number is 1234 5"
In [147]: "wang's phone number is %(wang)s %(xx)d" %a
Out[147]: "wang's phone number is 1234 5"
if语句:空字符串会很方便
In [151]: bool([])
Out[151]: False
In [152]: bool([1])
Out[152]: True
In [153]: if []: # False
print('ok')
for else循环:
格式: for 元素变量 in 可迭代对象
example:
for i in [1,2,3,'alex']:
print(i)
if else的类三元运算符:
In [153]: print('ok') if 3>1 else print('not ok')
ok
In [154]: print('ok') if 3<1 else print('not ok')
not ok
In [156]: 'ok' if 3<1 else 'not ok'
Out[156]: 'not ok'
In [157]: 'ok' if 3>1 else 'not ok'
Out[157]: 'ok'
In [160]: a = 1 if 3<5 else 4
In [161]: a
Out[161]: 1
In [162]: a = 1 if 3>5 else 4
In [163]: a
Out[163]: 4
字典的妙用,不用再去用循环实现