set集合

​set是一个无序且不重复的元素集合,访问速度快,天生解决重复问题

s1 = set()

s1.add('luo')​

s2 = set (['luo','wu','wei','ling'])

​s3 = s2.difference(['luo','wu'])            #s2中数据拿来逐个匹配,不同的被赋值给s3

​s2.difference_update(['luo','wu'])       #s2数据逐个匹配,修改s2

difference:不修改原来集合,创建一个新的集合

difference_update:修改原集合,不需要赋值,如赋值,返回值为None

s2.pop()         #随机删除一个数据​,没有返回值

s2.remove('luo')     #移除数据luo,可以赋值给变量​

例:​

# 数据库中原有

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 }

​​}

​old = set(old_dict.keys())

new = set(new_dict.keys())​

交集:​把old和new相同的元素取出来赋值给update_set

update_set = old.intersection(new)

差集:​从old中拿出和update_set相同的数据,old中不同的数值赋值给delete

delete_set = old.difference(update_set)​​

add_set = new.difference(update_set)​

对称差:把new和update_set不同的都拿出来

​delete_set = old.symmetric_difference(update_set)​​

add_set = new.symmetric_difference(update_set)​

collections​

​一、计数器(counter)

Counter是对字典类型的补充,用于追踪值的出现次数​

ps:具备字典的所有功能 + 自己的功能

import collections​

= collections​.Counter('abcdeabcdabcaba')

print c

输出:Counter({'a'5'b'4'c'3'd'2'e'1})

c.update(['eric','11','11'])​ #添加元素到变量c

c.subtract(['11','eric'])​   #删除变量c里面的这些元素

​for k in c.elements():                 #elements是元素,取出里面所有元素

print (k)

for k,v in c.items():                    #取key和values

print (k,v)​

二、有序字典​

函数​

def 函数名(参数):    

    ...

    函数体

    ...

函数的定义主要有如下要点:

  • def:表示函数的关键字
    • 函数名:函数的名称,日后根据函数名调用函数
    • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最                大数等...
    • 参数:为函数体提供数据
    • 返回值:当函数执行完毕后,可以给调用者返回数据。return是关键字,默认为None,return以下的代码是不会执行的

def show():

  print('a')

  return 123          #返回值是123,下面的print('b')不会执行

  print('b')​

​f = show()​​​

print (f​)             #会有'a'和123

函数的普通参数

user为形式参数,最后面的mail()括号的为实际参数

#!/usr/bin/env python
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(['武沛齐','wptawy@126.com'])
msg['To'] = formataddr(['走人','123456789@qq.com'])
msg['Subject'] = '主题'
server = smtplib.SMTP("smtp.126.com",25)
server.login("wptawy@126.com","WW.3945.59")
server.sendmail("wptawy@126.com",[user,],msg.as_string())
server.quit()
except Exception:
ret = False
return ret
ret = mail('123456789@qq.com') #输入要发送的用户名
if ret:
print("发送成功")
else:
print("发送失败")

多个参数

#!/usr/bin/env python

#一个参数
def show(arg):
print (arg)
show("kkkkkk") #两个参数
def show(arg,xxx):
print (arg,xxx)
show("kkkkkk","")

函数的默认参数:

默认参数必须放在最后,如果给a2赋值,那么a2的默认值会被覆盖

def show(a1,a2=999):
print (a1,a2)
show(111)
show(111,888)

指定参数:

def show(a1,a2):
print (a1,a2)
show (a2=123,a1=999)

函数的动态参数:

实际参数可以是“元组”,“列表”,"字典"

一个"*"默认是”元组"

两个"*"默认是”字典“

def show(*arg):
print (arg,type(arg))
show(1,2,3,4,5,6)
>>>(1,2,3,4,5,6)<class 'tuple'>
def show(**arg):
print (arg,type(arg))
show (n1=78,uu=123,bb=999)
>>>{'bb':999,'n1':78,'uu':123}<class'dict'>

还可以“*”,“**”组合使用,"**"必须放在“*”后面

def show(*args,**kwargs):
print (args,type(args))
print (kwargs,type(kwargs))
show (11,22,33,44,n1=88,luo='stupid')

如果要把一个字典和一个列表分别放进(*arg和**kwargs),就分别在字典和列表的变量加对应的*和**,如果没有加,那么都会放进args里。

def show(*args,**kwargs):
print (args,type(args))
print (kwargs,type(kwargs))
l = [,,,]
d = {'n1':,'luo':'stupid'}
show(*l,**d)

动态参数实现字符串格式化:

可以直接在括号里加参数,也可以用list和dict来实现。

s1 = "{0} is {1}"            #必须使用0和1
l = ['luo','stupid']
result = s1.format(*l) #返回值赋给result
print (result) s1 = "{name} is {acter}"
d = {'name':'luo','acter':'stupid'}
result = s1.format(**d)
print (result)

lambda表达式:

简单函数的简单表示

func = lambda  a: a+        #a是形式参数,可以是多个,冒号后面是函数体,并且返回return值
ret = func()
print (ret) #传统函数表达方式
def func(a):
a +=1
return a
result = func(99)
print (result)

常用内置函数:

enumerate()

l = ['luo','ling','feng']
for i,item in enumerate(l,): #结果加上序号,从1开始
print (i,item)

all():如果传入的所有元素都为真,才为真

bool():布尔值,None为假,空字符串,元组,列表,字典都为假

any():只要有一个元素是真,返回值为真

bin():二进制,将数字转换为二进制

bytearray():转换成字节数组

bytes():转换成字符串

callbable():检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功

chr():将数字转为asci码里的字符(一般用于随机验证码)

ord():将asci码的字符转换为数字(一般用于随机验证码)

dir():不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表

eval():将字符串str当成有效的表达式来求值并返回计算结果。例:左边的数据和右边的数据相乘,eval("6*8")

filter():对于序列中的元素进行筛选,最终获取符合条件的序列

li = [,,,]
def func(x):
if x>:
return True
else:
return False
n = filter(func,li)
print (list(n))
>>>[44]

map():遍历序列,对序列中每个元素进行操作,最终获取新的序列

li = [,,,]
new_li = map(lambda x:x+,li)
l = list(new_li)
print (l)
>>>[111,122,133,144]

open函数

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件

一、打开文件

1
文件句柄 = open('文件路径''模式')
 
 
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

二、操作

f.tell()     #查看当前指针位置

f.seek()    #指定当前指针位置

f.read()    #指定读取字符

f.truncate() #保留指针前面的内容,并且删除原文件指针之后的内容

python 3.x中read按字符读取,tell按字节查看。

python 2.x

class file(object)
def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return 0 def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass Python 2.x

python 3.x

class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict". newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string. If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default Python 3.x

Python学习路程day3的更多相关文章

  1. Python学习路程day18

    Python之路,Day18 - Django适当进阶篇 本节内容 学员管理系统练习 Django ORM操作进阶 用户认证 Django练习小项目:学员管理系统设计开发 带着项目需求学习是最有趣和效 ...

  2. Python学习路程day16

    Python之路,Day14 - It's time for Django 本节内容 Django流程介绍 Django url Django view Django models Django te ...

  3. Python学习路程day8

    Socket语法及相关 socket概念 A network socket is an endpoint of a connection across a computer network. Toda ...

  4. Python学习路程day6

    shelve 模块 shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式 import shelve d = shelve.open ...

  5. python 学习路程(一)

    好早之前就一直想学python,可是一直没有系统的学习过,给自己立个flag,从今天开始一步步掌握python的用法: python是一种脚本形式的语言,据说是面向废程序员学习开发使用的,我觉得很适合 ...

  6. Python学习路程-常用设计模式学习

    本节内容 设计模式介绍 设计模式分类 设计模式6大原则 1.设计模式介绍 设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复 ...

  7. Python学习路程day19

    Python之路,Day19 - Django 进阶   本节内容 自定义template tags 中间件 CRSF 权限管理 分页 Django分页 https://docs.djangoproj ...

  8. Python学习路程day15

    Python之路[第十五篇]:Web框架 Web框架本质 众所周知,对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端. #!/usr/bin/en ...

  9. Python学习路程day17

    常用算法与设计模式 选择排序 时间复杂度 二.计算方法 1.一个算法执行所耗费的时间,从理论上是不能算出来的,必须上机运行测试才能知道.但我们不可能也没有必要对每个算法都上机测试,只需知道哪个算法花费 ...

随机推荐

  1. [HBuilder] 简介

    官网首页: http://www.dcloud.io/runtime.html 特点: 编码比其他工具快5倍 代码输入法:按下数字快速选择候选项 可编程代码块:一个代码块,少敲50个按键 内置emme ...

  2. JAVA 多态和异常处理作业——动手动脑以及课后实验性问题

    1.  阅读以下代码(CatchWho.java),写出程序运行结果: 1)  源代码 public class CatchWho { public static void main(String[] ...

  3. python中cPickle的用法

    import cPickle as p f = file('data.txt' , 'w') data = (1 , 'A' , "hello") p.dump(data , f) ...

  4. 聚类算法:K-means 算法(k均值算法)

    k-means算法:      第一步:选$K$个初始聚类中心,$z_1(1),z_2(1),\cdots,z_k(1)$,其中括号内的序号为寻找聚类中心的迭代运算的次序号. 聚类中心的向量值可任意设 ...

  5. Objective-C(二、类和对象)

     类和对象 #import是include的升级版,可以自动防止重复包含,所以注意:大家以后在引入头文件的时候都使用import Foundation是一个框架,Foundation.h是Founda ...

  6. Java多线程-新特征-锁(上)

    在Java5中,专门提供了锁对象,利用锁可以方便的实现资源的封锁,用来控制对竞争资源并发访问的控制,这些内容主要集中在java.util.concurrent.locks 包下面,里面有三个重要的接口 ...

  7. 230. Kth Smallest Element in a BST ——迭代本质:a=xx1 while some_condition: a=xx2

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not ...

  8. linux tar 增量备份命令

    tar --newer-mtime "2013-09-17 00:00:00"   -zcvf /var/www/good.tar.gz    spider/

  9. Linux的五个查找命令(find、locate、whereis、which、type)

    1. find find是最常见和最强大的查找命令,你可以用它找到任何你想找的文件. find的使用格式如下: $ find <指定目录> <指定条件> <指定动作> ...

  10. 反质数(Antiprimes)

    转载http://www.cnblogs.com/tiankonguse/archive/2012/07/29/2613877.html 问题描述: 对于任何正整数x,起约数的个数记做g(x).例如g ...