My way to Python - Day03
dict1 = {}
dict1['k1'] = 'v1'
list1 = []
list1.append('v1')
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> c1 = collections.Counter()
>>> str1 = 'fujafksabfaskfjaslfl jshjfkk fhsfj hfajsjfsk fj'
>>> c1 = collections.Counter(str1)
>>> c1 # 对于字符串操作的结果是:为每个出现的字符计数
Counter({'f': 11, 'j': 8, 's': 7, 'a': 5, 'k': 5, ' ': 4, 'h': 3, 'l': 2, 'b': 1, 'u': 1})
>>> list1 = [11,22,22,33,33,33,44,44,44,44]
>>> c1 = collections.Counter(list1)
>>> c1 # 对于列表操作的结果是:为每个出现的元素计数
Counter({44: 4, 33: 3, 22: 2, 11: 1})
>>>
2,有序字典 orderedDict
dic ={}
dic = {'k1':[]} # → 这两行等同于下例中的一行(#←)
dic['k1'].append(1) # → 这两行等同于下例中的一行(#←)
from collections import defaultdict dic = collections.defaultdict(list) # ← dic['k1'].append(1)
默认字典操作样例:
>>> from collections import defaultdict # 使用默认字典,需要先导入defaultdict
>>> dic = {}
>>> dic = collections.defaultdict(list) # 创建一个默认字典对象,把字典的value的默认类型置为列表
>>> dic['k1'].append(1) # 向字典中添加一个key k1<list类型>,并向k1中append一个元素1
>>> dic
defaultdict(<type 'list'>, {'k1': [1]})
>>>
>>> dic1 = {'k1':1}
>>> dic1
{'k1': 1}
>>>
>>> dic1 = collections.defaultdict(list)
>>> dic1
defaultdict(<type 'list'>, {})
>>>
>>> dic1.append(22) # 直接对dict1做append操作会报错,因为字典不能通过append进行赋值
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'collections.defaultdict' object has no attribute 'append'
>>> dic1['k2'].append(22) # 可以对默认字典中的列表元素做append操作
>>> dic1
defaultdict(<type 'list'>, {'k2': [22]})
>>>
>>> Mytuple = collections.namedtuple('Mytuple',['x','y'])
>>>
>>> n = Mytuple(x=1,y=2)
>>> n.x
1
>>> n.y
2
>>>
help(Mytuple)
Help on class Mytuple in module __main__:
class Mytuple(__builtin__.tuple)
| Mytuple(x, y)
|
| Method resolution order:
| Mytuple
| __builtin__.tuple
| __builtin__.object
|
| Methods defined here:
|
| __getnewargs__(self)
| Return self as a plain tuple. Used by copy and pickle.
|
| __getstate__(self)
| Exclude the OrderedDict from pickling
|
| __repr__(self)
| Return a nicely formatted representation string
|
| _asdict(self)
| Return a new OrderedDict which maps field names to their values
|
| _replace(_self, **kwds)
| Return a new Mytuple object replacing specified fields with new values
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type
| Make a new Mytuple object from a sequence or iterable
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(_cls, x, y)
| Create new instance of Mytuple(x, y)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| Return a new OrderedDict which maps field names to their values
|
| x
| Alias for field number 0
|
| y
| Alias for field number 1
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| _fields = ('x', 'y')
|
| ----------------------------------------------------------------------
| Methods inherited from __builtin__.tuple:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __getslice__(...)
| x.__getslice__(i, j) <==> x[i:j]
|
| Use of negative indices is not supported.
|
| __gt__(...)
| x.__gt__(y) <==> x>y
|
| __hash__(...)
| x.__hash__() <==> hash(x)
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __le__(...)
| x.__le__(y) <==> x<=y
|
| __len__(...)
| x.__len__() <==> len(x)
|
| __lt__(...)
| x.__lt__(y) <==> x<y
|
| __mul__(...)
| x.__mul__(n) <==> x*n
|
| __ne__(...)
| x.__ne__(y) <==> x!=y
|
| __rmul__(...)
| x.__rmul__(n) <==> n*x
|
| __sizeof__(...)
| T.__sizeof__() -- size of T in memory, in bytes
|
| 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.
(END)
双向队列:deque
>>> import collections >>> q = collections.deque() >>> q.append(1) >>> q.append(2) >>> q.append(3) >>> q.append(4) >>> >>> q deque([1, 2, 3, 4]) >>> q.pop() 4 >>> q deque([1, 2, 3]) >>> q.popleft() # 此处要注意,是popleft而非leftpop 1 >>> q deque([2, 3]) >>> >>> q.appendleft(5) >>> q deque([5, 2, 3]) >>>
>>> import Queue >>> >>> q = Queue.Queue(10) >>> >>> q.put(1) >>> q.put(2) >>> q.put(3) >>> q <Queue.Queue instance at 0x7f3975f505a8> # 此处返回的是这个对象实例的内存地址 # 之所以没有返回队列中所有的元素是因为 # 在Queue的类的定义中没有实现__str__的方法。 >>> q.get() 1 >>> q.get() 2 >>> q.get() 3 >>> q.get() # 此时队列里已经没有元素了,再get则会hang住。 ^C^C
注意:在get时,如果过队列里面没有数据的时候,线程会hang住。
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
>>> help(list.__iter__)
Help on wrapper_descriptor:
__iter__(...)
x.__iter__() <==> iter(x)
(END)
# 打印列表的2种方法:
# 方法1 >>> li = [11,22,33,44,55,66] >>> for i in li: ... print i ... 11 22 33 44 55 66 >>> # 方法2 >>> li = [11,22,33,44,55,66] >>> for i in range(len(li)): ... print li[i] ... 11 22 33 44 55 66 >>>
生成器:
>>> >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> >>> xrange(10) xrange(10) >>>
辅助理解的类比:
# 基于range的冒泡排序算法
li = [13, 22, 6, 99, 11]
for m in range(len(li)-1):
for n in range(m+1, len(li)):
if li[m]> li[n]:
temp = li[n]
li[n] = li[m]
li[m] = temp
print li
>>> li = ['stephen','',25] >>> all(li) False >>> any(li) True >>> >>> li = ['stephen','password',25] >>> all(li) True >>> any(li) True >>> >>> li = [''] >>> all(li) False >>> any(li) False >>> >>>
ASCII码数字对照表
>>> li = [11,22,33,44,55,66] >>> for k,v in enumerate(li): ... print k,v ... 0 11 1 22 2 33 3 44 4 55 5 66 >>> >>> for k,v in enumerate(li,1): ... print k,v ... 1 11 2 22 3 33 4 44 5 55 6 66 >>> >>>
map等内置函数。。。
函数
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Stephen'
def email(arg):
#print arg
if __name__ == '__main__':
cpu = 99
ram = 50
disk = 95
for i in range(1):
if cpu > 90:
alert = 'cpu is ERROR'
email(alert)
if ram > 90:
alert = 'memory is ERROR'
email(alert)
if disk > 90:
alert = 'disk is ERROR'
email(alert)
程序运行结果:
C:\Python27\python.exe G:/python/day03/def_function.py cpu is ERROR disk is ERROR Process finished with exit code 0
修改为smtp的方式
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Stephen'
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
def email(arg): # 此处的arg为形式参数,简称形参。不赋值的时候没有实际意义。
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["Stephen",'xxx@126.com'])
msg['To'] = formataddr(["thatsit",'xxx@qq.com'])
msg['Subject'] = "监控报警邮件"
server = smtplib.SMTP("smtp.126.com", 25)
server.login("mail-address@126.com", "PASSWORD")
server.sendmail('xxx@126.com', ['xxx@qq.com',], msg.as_string())
server.quit()
if __name__ == '__main__':
cpu = 99
ram = 50
disk = 95
for i in range(10):
if cpu > 90:
alert = 'cpu is ERROR 第%d次' %i
email(alert) # 此处的alert在赋值之后就是实际参数。
if ram > 90:
alert = 'memory is ERROR 第%d次' %i
email(alert)
if disk > 90:
alert = 'disk is ERROR 第%d次' %i
email(alert)
def func(**kwargs):
print kwargs
func (k1=123,k2='sss')
dic = {k1:123,k2:234}
func (**dic)
文件打开方式:(#涉及到python升级的原因,推荐使用open的方式打开文件)
① obj = file('文件路径','打开模式')
② obj = open('文件路径','打开模式')
r,只读 w,清空原文件写 a,可读,可写,只能以追加的方式写 r+,可读可写 w+ <==> w a+ <==> a
文件指针操作样例
1 obj = open('log.txt','r') # 打开文件
2 obj.seek(5) # 指定文件的指针
3 print obj.tell() # 显示文件指针
4 obj.read() # 将文件全部加载到内存,此时的文件指针已经到了文件的尾部
5 print obj.tell() # 显示文件指针
执行结果:
C:\Python27\python.exe G:/python/day03/func.py 5 24 Process finished with exit code 0
文件其他操作
truncate() # 根据当前指针的位置截断数据,截断位置也可以使用参数指定。
# eg:truncate(5)
b # 二进制,在linux没有什么卵用,在跨平台的时候要用。
rU # U参数只能跟r结合。写法有rU和r+U两种。
# 用来处理不同平台的换行符的问题:处理不同平台的换行符的问题:(\n,\r,\r\n)。
托管资源:手动进行释放,在python中才有,用于同时打开同一个文件。
非托管资源:
closed() #关闭文件
flush() # 会把应用缓存写到系统缓存中,但是不一定会直接写到磁盘,依赖于系统机制
open() #打开文件:
next() # 取下一行,不存在会报错。
write() # 写文件
writelines() # 参数可以是一个列表
xreadlines() # 逐行读取文件
for line in f: # 用来替换for line in f.xreadlines()
with关键字,用来做上下文管理。并且with在python2.7之后支持同时打开多个配置文件。
obj = open('log','r')
with open('log','r') as obj:
My way to Python - Day03的更多相关文章
- Python Day03
set Collections系列: Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几 ...
- python———day03
一.字符串格式化输出: 占位符 %s(字符串) %d(整数) %f(浮点数,约等于小数) name = input("Name:") age = input("Ag ...
- python day03笔记总结
2019.3.29 S21 day03笔记总结 昨日回顾及补充 1.运算符补充 in not in 2.优先级 运算符与运算符之间也有优先级之分 今日内容 一.整型(int) py2 与 py3 的区 ...
- python day03作业
- 我的Python之旅第三天
一 编码操作 1 编码 enconde() 英文字符编码为"utf-8"时,一个字符占一个字节. s1='abcdef' b1=s1.encode('utf-8') print(b ...
- 【转】Python 内置函数 locals() 和globals()
Python 内置函数 locals() 和globals() 转自: https://blog.csdn.net/sxingming/article/details/52061630 1>这两 ...
- python操作haproxy.cfg文件
需求 1.查 输入:www.oldboy.org 获取当前backend下的所有记录 2.新建 输入: arg = { 'bakend': 'www.oldboy.org', 'record':{ ' ...
- Python基础-day03
写在前面 上课第三天,打卡: 不要让干净的灵魂染上尘埃,永远年轻.永远热泪盈眶 一.再谈编码 - 文件的概念 '文件' 是一个抽象的概念,是操作系统提供的外部存储设备的抽象,对应底层的硬盘:它是程序 ...
- python开发学习-day03(set集合、collection系列 、深浅拷贝、函数)
s12-20160116-day03 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...
随机推荐
- C#遍历Object各个属性含List泛型嵌套。
同事遇到一个问题:在做手机app接口时,返回JSON格式,json里面的数据属性均是string类型,但不能出现NULL(手机端那边说处理很麻烦,哎).Model已经创建好了,而且model的每个属性 ...
- JQuery或JavaScript获取网页的宽度、高等
最近多次使用JQery或JavaScript获取网页的宽度或者高度,在网上搜索N久之后发现很多都是粘贴上去并没有详细的介绍,这里我将会对经常使用的一些获取页面宽高的属性,方法做详细的介绍,以便能够更加 ...
- CSS基础知识之float
前段时间写过一篇CSS基础知识之position,当时对float的理解不太准确,被慕课网多名读者指出(原文已修正,如有误导实在抱歉).现对float进行更深入的学习,在此把学习心得分享给大家. 浮动 ...
- NFinal 视图—模板
创建模板 1.新建Header.ascx用户控件,此控件就是模板,修改内容如下: <%@ Control Language="C#" AutoEventWireup=&quo ...
- compilation 元素(ASP.NET 设置架构)
配置 ASP.NET 用于编译应用程序的所有编译设置. <configuration> 元素 system.web 元素(ASP.NET 设置架构) compilation 元素( ...
- java web实现img读取盘符下的图像
最近做了一个项目,用户上传图片后通过img控件显示出来.大家都知道img通过src属性就可以显示图片.如<img src="http://127.0.0.1/a/b/abc.jpg&q ...
- Access restriction: The type * is not accessible due to restrict,报错问题
解决方案1: Eclipse 默认把这些受访问限制的API设成了ERROR. Windows -> Preferences -> Java -> Compiler -> Er ...
- mysql查询分组归类函数-group_concat,通常与group_by一起使用
select a.`name`,group_concat(b.name SEPARATOR'.') as persons from `group` as a,`person` as b,`person ...
- 在html页头设置不缓存
方法一:在<head>标签里增加如下meta标签. <meta http-equiv="Content-Type" content="text/html ...
- Cogs 12 运输问题2 (有上下界网络流)
#include <cstdlib> #include <algorithm> #include <cstring> #include <iostream&g ...