PYTHON之路(三)

 



set是一个无序且不重复的元素集合

add
clear
copy
difference
difference_update
discard
intersection
intersection_update
isdisjoint
isdubset
issuperset
pop
remove
symmetric_difference
symmetric_difference_update
union
update

class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
""" 添加 """
"""
Add an element to a set.

This has no effect if the element is already present.
"""
pass

def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass

def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass

def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)
"""
pass

def difference_update(self, *args, **kwargs): # real signature unknown
""" 删除当前set中的所有包含在 new set 里的元素 """
""" Remove all elements of another set from this set. """
pass

def discard(self, *args, **kwargs): # real signature unknown
""" 移除元素 """
"""
Remove an element from a set if it is a member.

If the element is not a member, do nothing.
"""
pass

def intersection(self, *args, **kwargs): # real signature unknown
""" 取交集,新创建一个set """
"""
Return the intersection of two or more sets as a new set.

(i.e. elements that are common to all of the sets.)
"""
pass

def intersection_update(self, *args, **kwargs): # real signature unknown
""" 取交集,修改原来set """
""" Update a set with the intersection of itself and another. """
pass

def isdisjoint(self, *args, **kwargs): # real signature unknown
""" 如果没有交集,返回true """
""" Return True if two sets have a null intersection. """
pass

def issubset(self, *args, **kwargs): # real signature unknown
""" 是否是子集 """
""" Report whether another set contains this set. """
pass

def issuperset(self, *args, **kwargs): # real signature unknown
""" 是否是父集 """
""" Report whether this set contains another set. """
pass

def pop(self, *args, **kwargs): # real signature unknown
""" 移除 """
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass

def remove(self, *args, **kwargs): # real signature unknown
""" 移除 """
"""
Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.
"""
pass

def symmetric_difference(self, *args, **kwargs): # real signature unknown
""" 差集,创建新对象"""
"""
Return the symmetric difference of two sets as a new set.

(i.e. all elements that are in exactly one of the sets.)
"""
pass

def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" 差集,改变原来 """
""" Update a set with the symmetric difference of itself and another. """
pass

def union(self, *args, **kwargs): # real signature unknown
""" 并集 """
"""
Return the union of sets as a new set.

(i.e. all elements that are in either set.)
"""
pass

def update(self, *args, **kwargs): # real signature unknown
""" 更新 """
""" Update a set with the union of itself and others. """
pass


set






old_set = set(old_dict.keys())
update_list = list(old_set.intersection(new_dict.keys()))

new_list = []
del_list = []

for i in new_dict.keys():
if i not in update_list:
new_list.append(i)

for i in old_dict.keys():
if i not in update_list:
del_list.append(i)

print update_list,new_list,del_list



collections系列

计数器(counter)
Counter是对字典类型的补充,用于追踪值的出现次数。
ps:具备字典的所有功能 + 自己的功能









有序字典(OrderedDict )
OrderedDict是对字典类型的补充,他记住了字典元素添加的顺序

class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.

# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three: [PREV, NEXT, KEY].


>>> import collections
>>> dic=collections.OrderedDict()
>>> dic['k1']='v1'
>>> dic['k2']='v2'
>>> print(dic)
OrderedDict([('k1', 'v1'), ('k2', 'v2')])
>>>




默认字典(defaultdict) 
defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。
class defaultdict(dict):
"""
defaultdict(default_factory[, ...]) --> dict with default factory

The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.
"""

from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = defaultdict(list)

for value in values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)



可命名元组(namedtuple) 
根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。

>>> import collections 
>>> Mytuple = collections.namedtuple('Mytuple',['x', 'y', 'z'])
>>> obj=Mytuple(11,22,33)
>>> print(obj.x)
11
>>> print(obj.y)
22
>>> print(obj.z)
33



双向队列(deque)
一个线程安全的双向队列
>>> d=collections.deque()
>>> d.append('aa')
>>> d.appendleft('bb')
>>> d
deque(['bb', 'aa'])
>>>






单项队列(先进先出 FIFO )
>>> import queue
>>> q=queue.Queue()
>>> q.put('123')
>>> q.put('456')
>>> q
<queue.Queue object at 0x7f054191f2e8>
>>> q.get()
'123'
>>> q.get()
'456'
>>>












深浅拷贝
对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址

>>> a1='aaaabbb'
>>> a2=a1
>>> print(id(a1))
139660551648400
>>> a1='aaaabbb'
>>> a2=a1
>>> print(id(a1),id(a2))
139660551648400 139660551648400
>>> import copy
>>> a3=copy.copy(a1)
>>> print(id(a1),id(a3))
139660551648400 139660551648400
>>> a4=copy.deepcopy(a1)
>>> print(id(a1),id(a4))
139660551648400 139660551648400
>>>




对于字典、元组、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

赋值:
>>> n1={'k1':'v1','k2':'v2','k3':['v3','v33']}
>>> n2=n1
>>> print(id(n1),id(n2))
139660612704840 139660612704840
>>>

 




浅拷贝只拷贝第一层
>>> n3=copy.copy(n1)
>>> print(id(n1),id(n3))
139660612704840 139660551653704
>>> print(id(n1['k3']),id(n3['k3']))
139660583839944 139660583839944
>>> print(id(n1['k1']),id(n3['k1']))
139660612758752 139660612758752
>>>



深拷贝是在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)
>>> n4=copy.deepcopy(n1)
>>> print(id(n1),id(n4))
139660612704840 139660584257096
>>> print(id(n1['k1']),id(n4['k1']))
139660612758752 139660612758752
>>> print(id(n1['k3']),id(n4['k3']))
139660583839944 139660551580744
>>>









>>> n1['k3'][0]='v333'
>>> n1
{'k1': 'v1', 'k2': 'v2', 'k3': ['v333', 'v33']}
>>> n3
{'k1': 'v1', 'k2': 'v2', 'k3': ['v333', 'v33']}
>>> n4
{'k1': 'v1', 'k2': 'v2', 'k3': ['v3', 'v33']}
>>> unset n1
File "<stdin>", line 1
unset n1
^
SyntaxError: invalid syntax
>>> n1.clear()
>>> n3
{'k1': 'v1', 'k2': 'v2', 'k3': ['v333', 'v33']}
>>> n1
{}
>>> del n1
>>> n3
{'k1': 'v1', 'k2': 'v2', 'k3': ['v333', 'v33']}
>>> n4
{'k1': 'v1', 'k2': 'v2', 'k3': ['v3', 'v33']}
>>> n2
{}
>>> n1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n1' is not defined
>>>




函数
形式参数,默认参数,动态参数

默认参数
>>> def show(arg,arg1=99):
... print(arg,arg1)
...
>>> show(2)
2 99
>>> show(2,arg1=0)
2 0
>>> show(arg1=8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: show() missing 1 required positional argument: 'arg'
>>> show(arg1=8,2)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>>

动态参数, *args表示传入的参数会变成一个元组; **kwargs表示传入的参数会变成字典
>>> def show(*args,**kwargs):
... print(args,type(args))
... print(kwargs,type(kwargs))
...
>>> show(1,2,3,a=1,b=2)
(1, 2, 3) <class 'tuple'>
{'b': 2, 'a': 1} <class 'dict'>
>>> show(1,2,3,'a'=1,'b'=2)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
>>> show(1,2,a=1,b=2,3)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>> show(1,2,3,)
(1, 2, 3) <class 'tuple'>
{} <class 'dict'>
>>> show(1,2,a=None,3)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>> show(a=1,b=2)
() <class 'tuple'>
{'b': 2, 'a': 1} <class 'dict'>
>>>

>>> l=[1,2,3]
>>> d={'a':'aa'}
>>> show(l,d)
([1, 2, 3], {'a': 'aa'}) <class 'tuple'>
{} <class 'dict'>
>>> show(*l,**d)
(1, 2, 3) <class 'tuple'>
{'a': 'aa'} <class 'dict'>
>>>


使用动态参数实现字符串格式化
>>> s='{0} is {1}'
>>> result=s.format('alex','cool')
>>> print(result)
alex is cool
>>> l=['alex','cool']
>>> result=s.format(*l)
>>> print(result)
alex is cool
>>> s='{name} is {actor}'
>>> result=s.format(name='alex',actor='coo')
>>> print(result)
alex is coo
>>> d={'name':'alex','actor':'coo'}
>>> result=s.format(**d)
>>> print(result)
alex is coo
>>>


lambda表达式









eval
map
filter
zip
open

>>> eval("5*6")
30
>>> li=[11,22,33]
>>> new_li=map(lambda x:x+10,li)
>>> list(new_li)
[21, 32, 43]
>>> def func(x):
... if x>22:
... return True
... else:
... return False
...
>>> new_li=filter(func,li)
>>> list(new_li)
[33]
>>>
>>> new_li=li
>>> new=zip(li,new_li)
>>> list(new)
[(11, 11), (22, 22), (33, 33)]
>>>

python3 file operation
read操作的是字符
seek and tell操作的是字节
truncate截断后面的,留下当前为止的,更新到文件里

>>> f=open('test','r')
>>> f.read()
'aaabbbcccdddeee'
>>> f=open('test','r')
>>> f.read(2)
'aa'
>>> f.tell()
2
>>> f.seek(5)
5
>>> f.read()
'bcccdddeee'


>>> f=open('test','r+')
>>> f.seek(6)
6
>>> f.truncate()
6
>>> f.read()
''
>>> f=open('test','r')
>>> f.read()
'aaabbb'
>>>











posted on 2016-02-01 19:23  251744647  阅读(196)  评论(0编辑  收藏  举报

导航