Python高手之路【三】python基础之函数
基本数据类型补充:
set 是一个无序且不重复的元素集合
class set(object):<br/> """<br/> set() -> new empty set object<br/> set(iterable) -> new set object Build an unordered collection of unique elements.<br/> """<br/> def add(self, *args, **kwargs): # real signature unknown<br/> """<br/> Add an element to a set,添加元素 This has no effect if the element is already present.<br/> """<br/> pass def clear(self, *args, **kwargs): # real signature unknown<br/> """ Remove all elements from this set. 清除内容"""<br/> pass def copy(self, *args, **kwargs): # real signature unknown<br/> """ Return a shallow copy of a set. 浅拷贝 """<br/> pass def difference(self, *args, **kwargs): # real signature unknown<br/> """<br/> Return the difference of two or more sets as a new set. A中存在,B中不存在 (i.e. all elements that are in this set but not the others.)<br/> """<br/> pass def difference_update(self, *args, **kwargs): # real signature unknown<br/> """ Remove all elements of another set from this set. 从当前集合中删除和B中相同的元素"""<br/> pass def discard(self, *args, **kwargs): # real signature unknown<br/> """<br/> Remove an element from a set if it is a member. If the element is not a member, do nothing. 移除指定元素,不存在不保错<br/> """<br/> pass def intersection(self, *args, **kwargs): # real signature unknown<br/> """<br/> Return the intersection of two sets as a new set. 交集 (i.e. all elements that are in both sets.)<br/> """<br/> pass def intersection_update(self, *args, **kwargs): # real signature unknown<br/> """ Update a set with the intersection of itself and another. 取交集并更更新到A中 """<br/> pass def isdisjoint(self, *args, **kwargs): # real signature unknown<br/> """ Return True if two sets have a null intersection. 如果没有交集,返回True,否则返回False"""<br/> pass def issubset(self, *args, **kwargs): # real signature unknown<br/> """ Report whether another set contains this set. 是否是子序列"""<br/> pass def issuperset(self, *args, **kwargs): # real signature unknown<br/> """ Report whether this set contains another set. 是否是父序列"""<br/> pass def pop(self, *args, **kwargs): # real signature unknown<br/> """<br/> Remove and return an arbitrary set element.<br/> Raises KeyError if the set is empty. 移除元素<br/> """<br/> pass def remove(self, *args, **kwargs): # real signature unknown<br/> """<br/> Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. 移除指定元素,不存在保错<br/> """<br/> pass def symmetric_difference(self, *args, **kwargs): # real signature unknown<br/> """<br/> Return the symmetric difference of two sets as a new set. 对称差集 (i.e. all elements that are in exactly one of the sets.)<br/> """<br/> pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown<br/> """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """<br/> pass def union(self, *args, **kwargs): # real signature unknown<br/> """<br/> Return the union of sets as a new set. 并集 (i.e. all elements that are in either set.)<br/> """<br/> pass def update(self, *args, **kwargs): # real signature unknown<br/> """ Update a set with the union of itself and others. 更新 """<br/> pass
1:创建
s = set()<br/> s = {11,22,33,55}
2:转换
li = [11,22,33,44]<br/> tu = (11,22,33,44)<br/> st = ''<br/> s = set(li)
3:intersection , intersection_update方法
a = {11,22,33,44}<br/> b = {22,66,77,88}<br/> ret = a.intersection(b)<br/> print(ret)
intersection取得两个集合中的交集元素,并将这些元素以一个新的集合返回给一个变量接收
a = {11,22,33,44}<br/> b = {22,66,77,88}<br/> a.intersection_update(b)<br/> print(a)
intersection_update取得两个集合的交集元素,并更新a集合
4:isdisjoint , issubset , issuperset方法
s = {11,22,33,44}<br/> b = {11,22,77,55}<br/> ret = s.isdisjoint(b)#有交集返回False,没有交集返回True<br/> print(ret)<br/> ## False
issubset判断是否为子集
a = {11,22,33,44}<br/> b = {11,44}<br/> ret = b.issubset(a)<br/> print(ret)<br/> ##########################################<br/> True
issuperset判断是否为父集
a = {11,22,33,44}<br/> b = {11,44}<br/> ret = a.issubset(b)<br/> print(ret)<br/> ##########################################<br/> False
5:discard , remove , pop
s = {11,22,33,44}<br/> s.remove(11)<br/> print(s)<br/> s.discard(22)<br/> print(s)<br/> s.pop()<br/> print(s)
三者都能达到移除元素的效果,区别在于remove移除集合中不存在的元素时会报错,discard移除不存在的元素是不会报错,pop无法精确控制移除哪个元素,按其自身的规则随机移除元素,返回被移除的元素,可以使用变量接收其返回值
6:symmetric_difference取差集
s = {11,22,33,44}<br/> b = {11,22,77,55}<br/> r1 = s.difference(b)<br/> r2 = b.difference(s)<br/> print(r1)<br/> print(r2)<br/> ret = s.symmetric_difference(b)<br/> print(ret)<br/> ## set([33, 44])<br/> ## set([77, 55])<br/> ## set([33, 44, 77, 55])
symmetric_difference返回两个集合中不是交集的元素
上面的代码中,将symmetric_difference换成symmetric_difference_update则表示将两个集合中不是交集的部分赋值给s
7:union , update方法
s = {11,22,33,44}<br/> b = {11,22,77,55}<br/> ret = s.union(b)<br/> print(ret)<br/> ## set([33, 11, 44, 77, 22, 55])
union方法合并两个集合
s = {11,22,33,44}<br/> b = {11,22,77,55}<br/> s.update(b)<br/> print(s)<br/> ## set([33, 11, 44, 77, 22, 55])
update方法更新s集合,将b集合中的元素添加到s集合中!update方法也可以传递一个列表,如:update([23,45,67])
练习题:有下面两个字典
要求:
1)两个字典中有相同键的,则将new_dict中的值更新到old_dict对应键的值
2)old_dict中存在的键且new_dict中没有的键,在old_dict中删除,并把new_dict中的键值更新到old_dict中
3)最后输出old_dict
# 数据库中原有<br/> old_dict = {<br/> "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },<br/> "#2":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },<br/> "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 }<br/> } # cmdb 新汇报的数据<br/> new_dict = {<br/> "#1":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 800 },<br/> "#3":{ 'hostname':'c1', 'cpu_count': 2, 'mem_capicity': 80 },<br/> "#4":{ 'hostname':'c2', 'cpu_count': 2, 'mem_capicity': 80 }<br/> }
old_keys = set(old_dict.keys())<br/> new_keys = set(new_dict.keys())<br/> #需要更新元素的键<br/> update_keys = old_keys.intersection(new_keys)<br/> print(update_keys)<br/> #需要删除元素的键<br/> del_keys = old_keys.difference(new_keys)<br/> #需要添加元素的键<br/> add_keys = new_keys.difference(old_keys)<br/> print(del_keys)<br/> print(add_keys)<br/> update_keys = list(update_keys)<br/> for i in update_keys :<br/> old_dict[i] = new_dict[i]<br/> del_keys = list(del_keys)<br/> for j in del_keys :<br/> del old_dict[j]<br/> for k in list(add_keys) :<br/> old_dict[k] = new_dict[k]<br/> print(old_dict)<br/> ########################################<br/> {'#3': {'hostname': 'c1', 'cpu_count': , 'mem_capicity': }, '#1': {'hostname': 'c1', 'cpu_count': , 'mem_capicity': }, '#4': {'hostname': 'c2', 'cpu_count': , 'mem_capicity': }}
答案
collections系列
一、计数器(counter)
Counter是对字典类型的补充,用于追踪值的出现次数。
ps:具备字典的所有功能 + 自己的功能
c = Counter('abcdeabcdabcaba')<br/> print c<br/> 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
########################################################################<br/> ### Counter<br/> ######################################################################## class Counter(dict):<br/> '''Dict subclass for counting hashable items. Sometimes called a bag<br/> or multiset. Elements are stored as dictionary keys and their counts<br/> are stored as dictionary values. >>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # three most common elements<br/> [('a', 5), ('b', 4), ('c', 3)]<br/> >>> sorted(c) # list all unique elements<br/> ['a', 'b', 'c', 'd', 'e']<br/> >>> ''.join(sorted(c.elements())) # list elements with repetitions<br/> 'aaaaabbbbcccdde'<br/> >>> sum(c.values()) # total of all counts >>> c['a'] # count of letter 'a'<br/> >>> for elem in 'shazam': # update counts from an iterable<br/> ... c[elem] += 1 # by adding 1 to each element's count<br/> >>> c['a'] # now there are seven 'a'<br/> >>> del c['b'] # remove all 'b'<br/> >>> c['b'] # now there are zero 'b' >>> d = Counter('simsalabim') # make another counter<br/> >>> c.update(d) # add in the second counter<br/> >>> c['a'] # now there are nine 'a' >>> c.clear() # empty the counter<br/> >>> c<br/> Counter() Note: If a count is set to zero or reduced to zero, it will remain<br/> in the counter until the entry is deleted or the counter is cleared: >>> c = Counter('aaabbc')<br/> >>> c['b'] -= 2 # reduce the count of 'b' by two<br/> >>> c.most_common() # 'b' is still in, but its count is zero<br/> [('a', 3), ('c', 1), ('b', 0)] '''<br/> # References:<br/> # http://en.wikipedia.org/wiki/Multiset<br/> # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html<br/> # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm<br/> # http://code.activestate.com/recipes/259174/<br/> # Knuth, TAOCP Vol. II section 4.6.3 def __init__(self, iterable=None, **kwds):<br/> '''Create a new, empty Counter object. And if given, count elements<br/> from an input iterable. Or, initialize the count from another mapping<br/> of elements to their counts. >>> c = Counter() # a new, empty counter<br/> >>> c = Counter('gallahad') # a new counter from an iterable<br/> >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping<br/> >>> c = Counter(a=4, b=2) # a new counter from keyword args '''<br/> super(Counter, self).__init__()<br/> self.update(iterable, **kwds) def __missing__(self, key):<br/> """ 对于不存在的元素,返回计数器为0 """<br/> 'The count of elements not in the Counter is zero.'<br/> # Needed so that self[missing_item] does not raise KeyError<br/> return 0 def most_common(self, n=None):<br/> """ 数量大于等n的所有元素和计数器 """<br/> '''List the n most common elements and their counts from the most<br/> common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common(3)<br/> [('a', 5), ('b', 4), ('c', 3)] '''<br/> # Emulate Bag.sortedByCount from Smalltalk<br/> if n is None:<br/> return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)<br/> return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1)) def elements(self):<br/> """ 计数器中的所有元素,注:此处非所有元素集合,而是包含所有元素集合的迭代器 """<br/> '''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC')<br/> >>> sorted(c.elements())<br/> ['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1<br/> >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})<br/> >>> product = 1<br/> >>> for factor in prime_factors.elements(): # loop over factors<br/> ... product *= factor # and multiply them<br/> >>> product Note, if an element's count has been set to zero or is a negative<br/> number, elements() will ignore it. '''<br/> # Emulate Bag.do from Smalltalk and Multiset.begin from C++.<br/> return _chain.from_iterable(_starmap(_repeat, self.iteritems())) # Override dict methods where necessary @classmethod<br/> def fromkeys(cls, iterable, v=None):<br/> # There is no equivalent method for counters because setting v=1<br/> # means that no element can have a count greater than one.<br/> raise NotImplementedError(<br/> 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') def update(self, iterable=None, **kwds):<br/> """ 更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一 """<br/> '''Like dict.update() but add counts instead of replacing them. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which')<br/> >>> c.update('witch') # add elements from another iterable<br/> >>> d = Counter('watch')<br/> >>> c.update(d) # add elements from another counter<br/> >>> c['h'] # four 'h' in which, witch, and watch '''<br/> # The regular dict.update() operation makes no sense here because the<br/> # replace behavior results in the some of original untouched counts<br/> # being mixed-in with all of the other counts for a mismash that<br/> # doesn't have a straight-forward interpretation in most counting<br/> # contexts. Instead, we implement straight-addition. Both the inputs<br/> # and outputs are allowed to contain zero and negative counts. if iterable is not None:<br/> if isinstance(iterable, Mapping):<br/> if self:<br/> self_get = self.get<br/> for elem, count in iterable.iteritems():<br/> self[elem] = self_get(elem, 0) + count<br/> else:<br/> super(Counter, self).update(iterable) # fast path when counter is empty<br/> else:<br/> self_get = self.get<br/> for elem in iterable:<br/> self[elem] = self_get(elem, 0) + 1<br/> if kwds:<br/> self.update(kwds) def subtract(self, iterable=None, **kwds):<br/> """ 相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量 """<br/> '''Like dict.update() but subtracts counts instead of replacing them.<br/> Counts can be reduced below zero. Both the inputs and outputs are<br/> allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('which')<br/> >>> c.subtract('witch') # subtract elements from another iterable<br/> >>> c.subtract(Counter('watch')) # subtract elements from another counter<br/> >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch<br/> >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch<br/> -1 '''<br/> if iterable is not None:<br/> self_get = self.get<br/> if isinstance(iterable, Mapping):<br/> for elem, count in iterable.items():<br/> self[elem] = self_get(elem, 0) - count<br/> else:<br/> for elem in iterable:<br/> self[elem] = self_get(elem, 0) - 1<br/> if kwds:<br/> self.subtract(kwds) def copy(self):<br/> """ 拷贝 """<br/> 'Return a shallow copy.'<br/> return self.__class__(self) def __reduce__(self):<br/> """ 返回一个元组(类型,元组) """<br/> return self.__class__, (dict(self),) def __delitem__(self, elem):<br/> """ 删除元素 """<br/> 'Like dict.__delitem__() but does not raise KeyError for missing values.'<br/> if elem in self:<br/> super(Counter, self).__delitem__(elem) def __repr__(self):<br/> if not self:<br/> return '%s()' % self.__class__.__name__<br/> items = ', '.join(map('%r: %r'.__mod__, self.most_common()))<br/> return '%s({%s})' % (self.__class__.__name__, items) # Multiset-style mathematical operations discussed in:<br/> # Knuth TAOCP Volume II section 4.6.3 exercise 19<br/> # and at http://en.wikipedia.org/wiki/Multiset<br/> #<br/> # Outputs guaranteed to only include positive counts.<br/> #<br/> # To strip negative and zero counts, add-in an empty counter:<br/> # c += Counter() def __add__(self, other):<br/> '''Add counts from two counters. >>> Counter('abbb') + Counter('bcc')<br/> Counter({'b': 4, 'c': 2, 'a': 1}) '''<br/> if not isinstance(other, Counter):<br/> return NotImplemented<br/> result = Counter()<br/> for elem, count in self.items():<br/> newcount = count + other[elem]<br/> if newcount > 0:<br/> result[elem] = newcount<br/> for elem, count in other.items():<br/> if elem not in self and count > 0:<br/> result[elem] = count<br/> return result def __sub__(self, other):<br/> ''' Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd')<br/> Counter({'b': 2, 'a': 1}) '''<br/> if not isinstance(other, Counter):<br/> return NotImplemented<br/> result = Counter()<br/> for elem, count in self.items():<br/> newcount = count - other[elem]<br/> if newcount > 0:<br/> result[elem] = newcount<br/> for elem, count in other.items():<br/> if elem not in self and count < 0:<br/> result[elem] = 0 - count<br/> return result def __or__(self, other):<br/> '''Union is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc')<br/> Counter({'b': 3, 'c': 2, 'a': 1}) '''<br/> if not isinstance(other, Counter):<br/> return NotImplemented<br/> result = Counter()<br/> for elem, count in self.items():<br/> other_count = other[elem]<br/> newcount = other_count if count < other_count else count<br/> if newcount > 0:<br/> result[elem] = newcount<br/> for elem, count in other.items():<br/> if elem not in self and count > 0:<br/> result[elem] = count<br/> return result def __and__(self, other):<br/> ''' Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc')<br/> Counter({'b': 1}) '''<br/> if not isinstance(other, Counter):<br/> return NotImplemented<br/> result = Counter()<br/> for elem, count in self.items():<br/> other_count = other[elem]<br/> newcount = count if count < other_count else other_count<br/> if newcount > 0:<br/> result[elem] = newcount<br/> return result Counter
Counter
二、有序字典(orderedDict )
orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
class OrderedDict(dict):<br/> 'Dictionary that remembers insertion order'<br/> # An inherited dict maps keys to values.<br/> # The inherited dict provides __getitem__, __len__, __contains__, and get.<br/> # The remaining methods are order-aware.<br/> # 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.<br/> # The circular doubly linked list starts and ends with a sentinel element.<br/> # The sentinel element never gets deleted (this simplifies the algorithm).<br/> # Each link is stored as a list of length three: [PREV, NEXT, KEY]. def __init__(self, *args, **kwds):<br/> '''Initialize an ordered dictionary. The signature is the same as<br/> regular dictionaries, but keyword arguments are not recommended because<br/> their insertion order is arbitrary. '''<br/> if len(args) > 1:<br/> raise TypeError('expected at most 1 arguments, got %d' % len(args))<br/> try:<br/> self.__root<br/> except AttributeError:<br/> self.__root = root = [] # sentinel node<br/> root[:] = [root, root, None]<br/> self.__map = {}<br/> self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__):<br/> 'od.__setitem__(i, y) <==> od[i]=y'<br/> # Setting a new item creates a new link at the end of the linked list,<br/> # and the inherited dictionary is updated with the new key/value pair.<br/> if key not in self:<br/> root = self.__root<br/> last = root[0]<br/> last[1] = root[0] = self.__map[key] = [last, root, key]<br/> return dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__):<br/> 'od.__delitem__(y) <==> del od[y]'<br/> # Deleting an existing item uses self.__map to find the link which gets<br/> # removed by updating the links in the predecessor and successor nodes.<br/> dict_delitem(self, key)<br/> link_prev, link_next, _ = self.__map.pop(key)<br/> link_prev[1] = link_next # update link_prev[NEXT]<br/> link_next[0] = link_prev # update link_next[PREV] def __iter__(self):<br/> 'od.__iter__() <==> iter(od)'<br/> # Traverse the linked list in order.<br/> root = self.__root<br/> curr = root[1] # start at the first node<br/> while curr is not root:<br/> yield curr[2] # yield the curr[KEY]<br/> curr = curr[1] # move to next node def __reversed__(self):<br/> 'od.__reversed__() <==> reversed(od)'<br/> # Traverse the linked list in reverse order.<br/> root = self.__root<br/> curr = root[0] # start at the last node<br/> while curr is not root:<br/> yield curr[2] # yield the curr[KEY]<br/> curr = curr[0] # move to previous node def clear(self):<br/> 'od.clear() -> None. Remove all items from od.'<br/> root = self.__root<br/> root[:] = [root, root, None]<br/> self.__map.clear()<br/> dict.clear(self) # -- the following methods do not depend on the internal structure -- def keys(self):<br/> 'od.keys() -> list of keys in od'<br/> return list(self) def values(self):<br/> 'od.values() -> list of values in od'<br/> return [self[key] for key in self] def items(self):<br/> 'od.items() -> list of (key, value) pairs in od'<br/> return [(key, self[key]) for key in self] def iterkeys(self):<br/> 'od.iterkeys() -> an iterator over the keys in od'<br/> return iter(self) def itervalues(self):<br/> 'od.itervalues -> an iterator over the values in od'<br/> for k in self:<br/> yield self[k] def iteritems(self):<br/> 'od.iteritems -> an iterator over the (key, value) pairs in od'<br/> for k in self:<br/> yield (k, self[k]) update = MutableMapping.update __update = update # let subclasses override update without breaking __init__ __marker = object() def pop(self, key, default=__marker):<br/> '''od.pop(k[,d]) -> v, remove specified key and return the corresponding<br/> value. If key is not found, d is returned if given, otherwise KeyError<br/> is raised. '''<br/> if key in self:<br/> result = self[key]<br/> del self[key]<br/> return result<br/> if default is self.__marker:<br/> raise KeyError(key)<br/> return default def setdefault(self, key, default=None):<br/> 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'<br/> if key in self:<br/> return self[key]<br/> self[key] = default<br/> return default def popitem(self, last=True):<br/> '''od.popitem() -> (k, v), return and remove a (key, value) pair.<br/> Pairs are returned in LIFO order if last is true or FIFO order if false. '''<br/> if not self:<br/> raise KeyError('dictionary is empty')<br/> key = next(reversed(self) if last else iter(self))<br/> value = self.pop(key)<br/> return key, value def __repr__(self, _repr_running={}):<br/> 'od.__repr__() <==> repr(od)'<br/> call_key = id(self), _get_ident()<br/> if call_key in _repr_running:<br/> return '...'<br/> _repr_running[call_key] = 1<br/> try:<br/> if not self:<br/> return '%s()' % (self.__class__.__name__,)<br/> return '%s(%r)' % (self.__class__.__name__, self.items())<br/> finally:<br/> del _repr_running[call_key] def __reduce__(self):<br/> 'Return state information for pickling'<br/> items = [[k, self[k]] for k in self]<br/> inst_dict = vars(self).copy()<br/> for k in vars(OrderedDict()):<br/> inst_dict.pop(k, None)<br/> if inst_dict:<br/> return (self.__class__, (items,), inst_dict)<br/> return self.__class__, (items,) def copy(self):<br/> 'od.copy() -> a shallow copy of od'<br/> return self.__class__(self) @classmethod<br/> def fromkeys(cls, iterable, value=None):<br/> '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.<br/> If not specified, the value defaults to None. '''<br/> self = cls()<br/> for key in iterable:<br/> self[key] = value<br/> return self def __eq__(self, other):<br/> '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive<br/> while comparison to a regular mapping is order-insensitive. '''<br/> if isinstance(other, OrderedDict):<br/> return dict.__eq__(self, other) and all(_imap(_eq, self, other))<br/> return dict.__eq__(self, other) def __ne__(self, other):<br/> 'od.__ne__(y) <==> od!=y'<br/> return not self == other # -- the following methods support python 3.x style dictionary views -- def viewkeys(self):<br/> "od.viewkeys() -> a set-like object providing a view on od's keys"<br/> return KeysView(self) def viewvalues(self):<br/> "od.viewvalues() -> an object providing a view on od's values"<br/> return ValuesView(self) def viewitems(self):<br/> "od.viewitems() -> a set-like object providing a view on od's items"<br/> return ItemsView(self) OrderedDict
OrderedDict
三、默认字典(defaultdict)
defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。
class defaultdict(dict):<br/> """<br/> defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce<br/> a new value when a key is not present, in __getitem__ only.<br/> A defaultdict compares equal to a dict with the same items.<br/> All remaining arguments are treated the same as if they were<br/> passed to the dict constructor, including keyword arguments.<br/> """<br/> def copy(self): # real signature unknown; restored from __doc__<br/> """ D.copy() -> a shallow copy of D. """<br/> pass def __copy__(self, *args, **kwargs): # real signature unknown<br/> """ D.copy() -> a shallow copy of D. """<br/> pass def __getattribute__(self, name): # real signature unknown; restored from __doc__<br/> """ x.__getattribute__('name') <==> x.name """<br/> pass def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__<br/> """<br/> defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce<br/> a new value when a key is not present, in __getitem__ only.<br/> A defaultdict compares equal to a dict with the same items.<br/> All remaining arguments are treated the same as if they were<br/> passed to the dict constructor, including keyword arguments. # (copied from class doc)<br/> """<br/> pass def __missing__(self, key): # real signature unknown; restored from __doc__<br/> """<br/> __missing__(key) # Called by __getitem__ for missing key; pseudo-code:<br/> if self.default_factory is None: raise KeyError((key,))<br/> self[key] = value = self.default_factory()<br/> return value<br/> """<br/> pass def __reduce__(self, *args, **kwargs): # real signature unknown<br/> """ Return state information for pickling. """<br/> pass def __repr__(self): # real signature unknown; restored from __doc__<br/> """ x.__repr__() <==> repr(x) """<br/> pass default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None) # default<br/> """Factory for default value called by __missing__().""" defaultdict
defaultdict
使用方法:
import collections<br/> dic = collections.defaultdict(list)<br/> dic['k1'].append('alext')<br/> print(dic)
练习:
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。<br/> 即: {'k1': 大于66 , 'k2': 小于66}
values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = {} for value in values:<br/> if value>66:<br/> if my_dict.has_key('k1'):<br/> my_dict['k1'].append(value)<br/> else:<br/> my_dict['k1'] = [value]<br/> else:<br/> if my_dict.has_key('k2'):<br/> my_dict['k2'].append(value)<br/> else:<br/> my_dict['k2'] = [value]
原生字典
from collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) for value in values:<br/> if value>66:<br/> my_dict['k1'].append(value)<br/> else:<br/> my_dict['k2'].append(value) defaultdict字典解决方法 默认字典
默认字典
四、可命名元组(namedtuple)
根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。
import collections<br/> MytupleClass = collections.namedtuple('MytupleClass',['x','y','z'])<br/> obj = MytupleClass(11,33,44)<br/> print(obj.x)<br/> print(obj.y)<br/> print(obj.z)
class Mytuple(__builtin__.tuple)<br/> | Mytuple(x, y)<br/> |<br/> | Method resolution order:<br/> | Mytuple<br/> | __builtin__.tuple<br/> | __builtin__.object<br/> |<br/> | Methods defined here:<br/> |<br/> | __getnewargs__(self)<br/> | Return self as a plain tuple. Used by copy and pickle.<br/> |<br/> | __getstate__(self)<br/> | Exclude the OrderedDict from pickling<br/> |<br/> | __repr__(self)<br/> | Return a nicely formatted representation string<br/> |<br/> | _asdict(self)<br/> | Return a new OrderedDict which maps field names to their values<br/> |<br/> | _replace(_self, **kwds)<br/> | Return a new Mytuple object replacing specified fields with new values<br/> |<br/> | ----------------------------------------------------------------------<br/> | Class methods defined here:<br/> |<br/> | _make(cls, iterable, new=<built-in method __new__ of type object>, len=<built-in function len>) from __builtin__.type<br/> | Make a new Mytuple object from a sequence or iterable<br/> |<br/> | ----------------------------------------------------------------------<br/> | Static methods defined here:<br/> |<br/> | __new__(_cls, x, y)<br/> | Create new instance of Mytuple(x, y)<br/> |<br/> | ----------------------------------------------------------------------<br/> | Data descriptors defined here:<br/> |<br/> | __dict__<br/> | Return a new OrderedDict which maps field names to their values<br/> |<br/> | x<br/> | Alias for field number 0<br/> |<br/> | y<br/> | Alias for field number 1<br/> |<br/> | ----------------------------------------------------------------------<br/> | Data and other attributes defined here:<br/> |<br/> | _fields = ('x', 'y')<br/> |<br/> | ----------------------------------------------------------------------<br/> | Methods inherited from __builtin__.tuple:<br/> |<br/> | __add__(...)<br/> | x.__add__(y) <==> x+y<br/> |<br/> | __contains__(...)<br/> | x.__contains__(y) <==> y in x<br/> |<br/> | __eq__(...)<br/> | x.__eq__(y) <==> x==y<br/> |<br/> | __ge__(...)<br/> | x.__ge__(y) <==> x>=y<br/> |<br/> | __getattribute__(...)<br/> | x.__getattribute__('name') <==> x.name<br/> |<br/> | __getitem__(...)<br/> | x.__getitem__(y) <==> x[y]<br/> |<br/> | __getslice__(...)<br/> | x.__getslice__(i, j) <==> x[i:j]<br/> |<br/> | Use of negative indices is not supported.<br/> |<br/> | __gt__(...)<br/> | x.__gt__(y) <==> x>y<br/> |<br/> | __hash__(...)<br/> | x.__hash__() <==> hash(x)<br/> |<br/> | __iter__(...)<br/> | x.__iter__() <==> iter(x)<br/> |<br/> | __le__(...)<br/> | x.__le__(y) <==> x<=y<br/> |<br/> | __len__(...)<br/> | x.__len__() <==> len(x)<br/> |<br/> | __lt__(...)<br/> | x.__lt__(y) <==> x<y<br/> |<br/> | __mul__(...)<br/> | x.__mul__(n) <==> x*n<br/> |<br/> | __ne__(...)<br/> | x.__ne__(y) <==> x!=y<br/> |<br/> | __rmul__(...)<br/> | x.__rmul__(n) <==> n*x<br/> |<br/> | __sizeof__(...)<br/> | T.__sizeof__() -- size of T in memory, in bytes<br/> |<br/> | count(...)<br/> | T.count(value) -> integer -- return number of occurrences of value<br/> |<br/> | index(...)<br/> | T.index(value, [start, [stop]]) -> integer -- return first index of value.<br/> | Raises ValueError if the value is not present. Mytuple
Mytuple
五、双向队列(deque)
一个线程安全的双向队列
class deque(object):<br/> """<br/> deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints.<br/> """<br/> def append(self, *args, **kwargs): # real signature unknown<br/> """ Add an element to the right side of the deque. """<br/> pass def appendleft(self, *args, **kwargs): # real signature unknown<br/> """ Add an element to the left side of the deque. """<br/> pass def clear(self, *args, **kwargs): # real signature unknown<br/> """ Remove all elements from the deque. """<br/> pass def count(self, value): # real signature unknown; restored from __doc__<br/> """ D.count(value) -> integer -- return number of occurrences of value """<br/> return 0 def extend(self, *args, **kwargs): # real signature unknown<br/> """ Extend the right side of the deque with elements from the iterable """<br/> pass def extendleft(self, *args, **kwargs): # real signature unknown<br/> """ Extend the left side of the deque with elements from the iterable """<br/> pass def pop(self, *args, **kwargs): # real signature unknown<br/> """ Remove and return the rightmost element. """<br/> pass def popleft(self, *args, **kwargs): # real signature unknown<br/> """ Remove and return the leftmost element. """<br/> pass def remove(self, value): # real signature unknown; restored from __doc__<br/> """ D.remove(value) -- remove first occurrence of value. """<br/> pass def reverse(self): # real signature unknown; restored from __doc__<br/> """ D.reverse() -- reverse *IN PLACE* """<br/> pass def rotate(self, *args, **kwargs): # real signature unknown<br/> """ Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """<br/> pass def __copy__(self, *args, **kwargs): # real signature unknown<br/> """ Return a shallow copy of a deque. """<br/> pass def __delitem__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__delitem__(y) <==> del x[y] """<br/> pass def __eq__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__eq__(y) <==> x==y """<br/> pass def __getattribute__(self, name): # real signature unknown; restored from __doc__<br/> """ x.__getattribute__('name') <==> x.name """<br/> pass def __getitem__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__getitem__(y) <==> x[y] """<br/> pass def __ge__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__ge__(y) <==> x>=y """<br/> pass def __gt__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__gt__(y) <==> x>y """<br/> pass def __iadd__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__iadd__(y) <==> x+=y """<br/> pass def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__<br/> """<br/> deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints.<br/> # (copied from class doc)<br/> """<br/> pass def __iter__(self): # real signature unknown; restored from __doc__<br/> """ x.__iter__() <==> iter(x) """<br/> pass def __len__(self): # real signature unknown; restored from __doc__<br/> """ x.__len__() <==> len(x) """<br/> pass def __le__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__le__(y) <==> x<=y """<br/> pass def __lt__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__lt__(y) <==> x<y """<br/> pass @staticmethod # known case of __new__<br/> def __new__(S, *more): # real signature unknown; restored from __doc__<br/> """ T.__new__(S, ...) -> a new object with type S, a subtype of T """<br/> pass def __ne__(self, y): # real signature unknown; restored from __doc__<br/> """ x.__ne__(y) <==> x!=y """<br/> pass def __reduce__(self, *args, **kwargs): # real signature unknown<br/> """ Return state information for pickling. """<br/> pass def __repr__(self): # real signature unknown; restored from __doc__<br/> """ x.__repr__() <==> repr(x) """<br/> pass def __reversed__(self): # real signature unknown; restored from __doc__<br/> """ D.__reversed__() -- return a reverse iterator over the deque """<br/> pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__<br/> """ x.__setitem__(i, y) <==> x[i]=y """<br/> pass def __sizeof__(self): # real signature unknown; restored from __doc__<br/> """ D.__sizeof__() -- size of D in memory, in bytes """<br/> pass maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None) # default<br/> """maximum size of a deque or None if unbounded""" __hash__ = None deque deque
deque
注:既然有双向队列,也有单项队列(先进先出 FIFO )
class Queue:<br/> """Create a queue object with a given maximum size. If maxsize is <= 0, the queue size is infinite.<br/> """<br/> def __init__(self, maxsize=0):<br/> self.maxsize = maxsize<br/> self._init(maxsize)<br/> # mutex must be held whenever the queue is mutating. All methods<br/> # that acquire mutex must release it before returning. mutex<br/> # is shared between the three conditions, so acquiring and<br/> # releasing the conditions also acquires and releases mutex.<br/> self.mutex = _threading.Lock()<br/> # Notify not_empty whenever an item is added to the queue; a<br/> # thread waiting to get is notified then.<br/> self.not_empty = _threading.Condition(self.mutex)<br/> # Notify not_full whenever an item is removed from the queue;<br/> # a thread waiting to put is notified then.<br/> self.not_full = _threading.Condition(self.mutex)<br/> # Notify all_tasks_done whenever the number of unfinished tasks<br/> # drops to zero; thread waiting to join() is notified to resume<br/> self.all_tasks_done = _threading.Condition(self.mutex)<br/> self.unfinished_tasks = 0 def task_done(self):<br/> """Indicate that a formerly enqueued task is complete. Used by Queue consumer threads. For each get() used to fetch a task,<br/> a subsequent call to task_done() tells the queue that the processing<br/> on the task is complete. If a join() is currently blocking, it will resume when all items<br/> have been processed (meaning that a task_done() call was received<br/> for every item that had been put() into the queue). Raises a ValueError if called more times than there were items<br/> placed in the queue.<br/> """<br/> self.all_tasks_done.acquire()<br/> try:<br/> unfinished = self.unfinished_tasks - 1<br/> if unfinished <= 0:<br/> if unfinished < 0:<br/> raise ValueError('task_done() called too many times')<br/> self.all_tasks_done.notify_all()<br/> self.unfinished_tasks = unfinished<br/> finally:<br/> self.all_tasks_done.release() def join(self):<br/> """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the<br/> queue. The count goes down whenever a consumer thread calls task_done()<br/> to indicate the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.<br/> """<br/> self.all_tasks_done.acquire()<br/> try:<br/> while self.unfinished_tasks:<br/> self.all_tasks_done.wait()<br/> finally:<br/> self.all_tasks_done.release() def qsize(self):<br/> """Return the approximate size of the queue (not reliable!)."""<br/> self.mutex.acquire()<br/> n = self._qsize()<br/> self.mutex.release()<br/> return n def empty(self):<br/> """Return True if the queue is empty, False otherwise (not reliable!)."""<br/> self.mutex.acquire()<br/> n = not self._qsize()<br/> self.mutex.release()<br/> return n def full(self):<br/> """Return True if the queue is full, False otherwise (not reliable!)."""<br/> self.mutex.acquire()<br/> n = 0 < self.maxsize == self._qsize()<br/> self.mutex.release()<br/> return n def put(self, item, block=True, timeout=None):<br/> """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default),<br/> block if necessary until a free slot is available. If 'timeout' is<br/> a non-negative number, it blocks at most 'timeout' seconds and raises<br/> the Full exception if no free slot was available within that time.<br/> Otherwise ('block' is false), put an item on the queue if a free slot<br/> is immediately available, else raise the Full exception ('timeout'<br/> is ignored in that case).<br/> """<br/> self.not_full.acquire()<br/> try:<br/> if self.maxsize > 0:<br/> if not block:<br/> if self._qsize() == self.maxsize:<br/> raise Full<br/> elif timeout is None:<br/> while self._qsize() == self.maxsize:<br/> self.not_full.wait()<br/> elif timeout < 0:<br/> raise ValueError("'timeout' must be a non-negative number")<br/> else:<br/> endtime = _time() + timeout<br/> while self._qsize() == self.maxsize:<br/> remaining = endtime - _time()<br/> if remaining <= 0.0:<br/> raise Full<br/> self.not_full.wait(remaining)<br/> self._put(item)<br/> self.unfinished_tasks += 1<br/> self.not_empty.notify()<br/> finally:<br/> self.not_full.release() def put_nowait(self, item):<br/> """Put an item into the queue without blocking. Only enqueue the item if a free slot is immediately available.<br/> Otherwise raise the Full exception.<br/> """<br/> return self.put(item, False) def get(self, block=True, timeout=None):<br/> """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default),<br/> block if necessary until an item is available. If 'timeout' is<br/> a non-negative number, it blocks at most 'timeout' seconds and raises<br/> the Empty exception if no item was available within that time.<br/> Otherwise ('block' is false), return an item if one is immediately<br/> available, else raise the Empty exception ('timeout' is ignored<br/> in that case).<br/> """<br/> self.not_empty.acquire()<br/> try:<br/> if not block:<br/> if not self._qsize():<br/> raise Empty<br/> elif timeout is None:<br/> while not self._qsize():<br/> self.not_empty.wait()<br/> elif timeout < 0:<br/> raise ValueError("'timeout' must be a non-negative number")<br/> else:<br/> endtime = _time() + timeout<br/> while not self._qsize():<br/> remaining = endtime - _time()<br/> if remaining <= 0.0:<br/> raise Empty<br/> self.not_empty.wait(remaining)<br/> item = self._get()<br/> self.not_full.notify()<br/> return item<br/> finally:<br/> self.not_empty.release() def get_nowait(self):<br/> """Remove and return an item from the queue without blocking. Only get an item if one is immediately available. Otherwise<br/> raise the Empty exception.<br/> """<br/> return self.get(False) # Override these methods to implement other queue organizations<br/> # (e.g. stack or priority queue).<br/> # These will only be called with appropriate locks held # Initialize the queue representation<br/> def _init(self, maxsize):<br/> self.queue = deque() def _qsize(self, len=len):<br/> return len(self.queue) # Put a new item in the queue<br/> def _put(self, item):<br/> self.queue.append(item) # Get an item from the queue<br/> def _get(self):<br/> return self.queue.popleft() Queue.Queue
Queue.Queue
三元运算
三元运算(三目运算),是对简单的条件语句的缩写。
# 书写格式<br/> result = 值1 if 条件 else 值2<br/> # 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量
a = 1<br/> name = 'poe' if a == 1 else 'jet'<br/> print(name)
深浅拷贝
一、数字和字符串
对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。
import copy<br/> # ######### 数字、字符串 #########<br/> n1 = 123<br/> # n1 = "i am alex age 10"<br/> print(id(n1))<br/> # ## 赋值 ##<br/> n2 = n1<br/> print(id(n2))<br/> # ## 浅拷贝 ##<br/> n2 = copy.copy(n1)<br/> print(id(n2)) # ## 深拷贝 ##<br/> n3 = copy.deepcopy(n1)<br/> print(id(n3))
二、其他基本数据类型
对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。
1、赋值
赋值,只是创建一个变量,该变量指向原来内存地址,如:
n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n2 = n1
2、浅拷贝
浅拷贝,在内存中只额外创建第一层数据
import copy n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n3 = copy.copy(n1)
3、深拷贝
深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)
import copy n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} n4 = copy.deepcopy(n1)
函数
1:函数的定义
def 函数名(参数): ...<br/> 函数体<br/> ...<br/> 返回值
函数的定义主要有如下要点:
def:表示函数的关键字
函数名:函数的名称,日后根据函数名调用函数
函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等…
参数:为函数体提供数据
返回值:当函数执行完毕后,可以给调用者返回数据。
2:返回值
函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。
以上要点中,比较重要有参数和返回值:
def 发送短信(): 发送短信的代码... if 发送成功:<br/> return True<br/> else:<br/> return False while True: # 每次执行发送短信函数,都会将返回值自动赋值给result<br/> # 之后,可以根据result来写日志,或重发等操作 result = 发送短信()<br/> if result == False:<br/> 记录日志,短信发送失败...
3:参数
函数有三种不同的参数:
普通参数
# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参<br/> def func(name):<br/> print name # ######### 执行函数 #########<br/> # 'wupeiqi' 叫做函数func的实际参数,简称:实参<br/> func('poe')
默认参数
def func(name, age = 18): print "%s:%s" %(name,age) # 指定参数<br/> func('poe', 19)<br/> # 使用默认参数<br/> func('gin') 注:默认参数需要放在参数列表最后
动态参数
def f1(*a):<br/> print(a,type(a))<br/> f1(123,456,[1,2,3],'who')<br/> ## ((123, 456, [1, 2, 3], 'who'), <type 'tuple'>)
def func(**kwargs):<br/> print args<br/> # 执行方式一<br/> func(name='poe',age=18) # 执行方式二<br/> li = {'name':'poe', age:18, 'gender':'male'}<br/> func(**li)
def f1(*a,**b) :#一个星的参数必须在前,两个星的参数必须在后<br/> print(a,type(a))<br/> print(b,type(b))<br/> f1(11,22,33,k1=1234,k2=456)<br/> ## ((11, 22, 33), <type 'tuple'>)({'k2': 456, 'k1': 1234}, <type 'dict'>)
为动态参数传入列表,元组,字典:(注:这几种数据类型在函数传参的时候只有引用传递,没有值传递)
def f1(*args) :<br/> print(args,type(args))<br/> li = [1,2,3,4]<br/> f1(li)<br/> f1(*li)<br/> ## (([1, 2, 3, 4],), <type 'tuple'>)<br/> ## ((1, 2, 3, 4), <type 'tuple'>)
def f2(**kwargs) :<br/> print(kwargs,type(kwargs))<br/> dic = {'k1':123,'k2':456}<br/> f2(k1 = dic)<br/> f2(**dic)<br/> ## ({'k1': {'k2': 456, 'k1': 123}}, <type 'dict'>)<br/> ## ({'k2': 456, 'k1': 123}, <type 'dict'>)
4:内置函数
注:查看详细猛击这里
数据类型转换函数
- chr(i) 函数返回ASCII码对应的字符串
-
print(chr(65))<br/> print(chr(66))<br/> print(chr(65)+chr(66))<br/> ##########################################<br/> A<br/> B<br/> AB
- complex(real[,imaginary]) 函数可把字符串或数字转换为复数
-
print(complex("2+1j"))<br/> print(complex(""))<br/> print(complex(2,1))<br/> ##########################################<br/> (2+1j)<br/> (2+0j)<br/> (2+1j)
- float(x) 函数把一个数字或字符串转换成浮点数
-
print(float(12))<br/> print(float(12.2))<br/> ##########################################<br/> 12.0<br/> 12.2
- long(x[,base]) 函数把数字和字符串转换成长整数,base为可选的基数
- list(x) 函数可将序列对象转换成列表
- min(x[,y,z…]) 函数返回给定参数的最小值,参数可以为序列
- max(x[,y,z…]) 函数返回给定参数的最大值,参数可以为序列
- ord(x) 函数返回一个字符串参数的ASCII码或Unicode值
-
print(ord('a'))<br/> print(ord(u"A"))<br/> ##########################################<br/> 97<br/> 65
- str(obj) 函数把对象转换成可打印字符串
- tuple(x) 函数把序列对象转换成tuple
- type(x) 可以接收任何东西作为参数――并返回它的数据类型。整型、字符串、列表、字典、元组、函数、类、模块,甚至类型对象都可以作为参数被 type 函数接受
abs()函数:取绝对值
print(abs(-1.2))
all()函数与any函数:
all(iterable):如果iterable的任意一个元素为0、”、False,则返回False,否则返回True
print(all(['a','b','c','d']))#True<br/> print(all(['a','b','','d']))#False<br/> #注意:空元组、空列表返回值为True,这里要特别注意
any(iterable):如果iterable的所有元素都为0、”、False,则返回False,否则返回True
print(any(['a','b','c','d']))#True<br/> print(any(['a',0,' ',False]))#True<br/> print(any([0,'',False]))#False
ascii(object) 函数:
返回一个可打印的对象字符串方式表示,如果是非ascii字符就会输出\x,\u或\U等字符来表示。与python2版本里的repr()是等效的函数。
print(ascii(1))<br/> print(ascii('a'))<br/> print(ascii(123))<br/> print(ascii('中文'))#非ascii字符<br/> ##########################################<br/> 1<br/> 'a'<br/> 123<br/> '\u4e2d\u6587'
lambda表达式:
学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:
# 普通条件语句<br/> if 1 == 1:<br/> name = 'poe'<br/> else:<br/> name = 'bruce' # 三元运算<br/> name = 'poe' if 1 == 1 else 'bruce'
对于简单的函数,也存在一种简便的表示方式,即:lambda表达式
# ###################### 普通函数 ######################<br/> # 定义函数(普通方式)<br/> def func(arg):<br/> return arg + 1 # 执行函数<br/> result = func(123) # ###################### lambda ###################### # 定义函数(lambda表达式)<br/> my_lambda = lambda arg : arg + 1 # 执行函数<br/> result = my_lambda(123)
生成随机数:
import random<br/> chars = ''<br/> for i in range(4) :<br/> rand_num = random.randrange(0,4)<br/> if rand_num == 3 or rand_num == 1:<br/> rand_digit = random.randrange(0,10)<br/> chars += str(rand_digit)<br/> else:<br/> rand_case = random.randrange(65,90)<br/> case = chr(rand_case)<br/> chars += case<br/> print(chars)
filter函数
filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
例1,要从一个list [1, 4, 6, 7, 9, 12, 17]中删除偶数,保留奇数,首先,要编写一个判断奇数的函数:
# filter(fn,iterable)<br/> def is_odd(x) :<br/> return x % 2 == 1<br/> li = [1, 4, 6, 7, 9, 12, 17]<br/> result = filter(is_odd,li)<br/> print(result)<br/> ##########################################<br/> [1, 7, 9, 17]
例2:删除 列表中的None 或者空字符串
li = ['test', None, '', 'str', ' ', 'END']<br/> def is_not_empty(s) :<br/> return s and len(s.strip()) > 0<br/> print(filter(is_not_empty,li))<br/> ##########################################<br/> ['test', 'str', 'END']
例3:请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
import math<br/> def is_sqr(x) :<br/> return math.sqrt(x) % 1 == 0<br/> print filter(is_sqr,range(1,101))
以上三个函数都可以使用lambda表达式的写法来书写,如:
result = filter(lambda x : x % 2 == 1,[1,4,6,9,12,7,17])<br/> print(result)
map()函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回
例如,对于list [1, 2, 3, 4, 5, 6, 7, 8, 9]如果希望把list的每个元素都作平方,就可以用map()函数
li = [1, 2, 3, 4, 5, 6, 7, 8, 9]<br/> print(li)<br/> def f(x) :<br/> return x*x<br/> r = list(map(f,[1, 2, 3, 4, 5, 6, 7, 8, 9]))<br/> print(r)
注:在python3里面,map()的返回值已经不再是list,而是iterators, 所以想要使用,只用将iterator 转换成list 即可, 比如 list(map()) 。
进制转换函数(以下四个函数可以实现各进制间的互相转换)
bin(x) :将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer
oct(x):将一个整数转换成8进制字符串。如果传入浮点数或者字符串均会报错
hex(x):将一个整数转换成16进制字符串。
int():
- 传入数值时,调用其__int__()方法,浮点数将向下取整
-
print(int(3))#<br/> print(int(3.6))#
- 传入字符串时,默认以10进制进行转换
-
print(int(''))#
- 字符串中允许包含”+”、”-“号,但是加减号与数值间不能有空格,数值后、符号前可出现空格
-
print(int('+36'))#
- 传入字符串,并指定了进制,则按对应进制将字符串转换成10进制整数
-
print(int('',2))#<br/> print(int('0o7',8))#<br/> print(int('0x15',16))#
open函数,该函数用于文件处理
操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
一:打开文件
文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认】
- w,只写模式【不可读;不存在则创建;存在则清空内容;】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
f = open('test.log','r')<br/> data = f.read()<br/> f.close()<br/> print(data)
“+” 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
# r+ 模式<br/> f = open('test.log','r+',encoding='utf-8')<br/> print(f.tell())#打印当前指针所在的位置,此时为0<br/> data = f.read()<br/> print(data)<br/> print(f.tell())#此时当前指针在文件最末尾<br/> f.close()
# w+模式:先清空文件,再写入文件,写入文件后才可以读文件<br/> f = open('test.log','w+',encoding="utf-8")<br/> f.write('python')#写完后,指针到了最后<br/> f.seek(0)#移动指针到开头<br/> data = f.read()<br/> f.close()<br/> print(data)
# a+模式:打开的同时,指针已经到最后,<br/> # 写时,追加,指针到最后<br/> f = open('test.log','a+',encoding="utf-8")<br/> print(f.tell())#读取当前指针位置,此时指针已经到最后<br/> f.write('c++')<br/> print(f.tell())<br/> #此时要读文件必须把指针移动到文件开头<br/> f.seek(0)<br/> data = f.read();<br/> print(data)<br/> f.close()
“b”表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
二:文件操作
class file(object)<br/> def close(self): # real signature unknown; restored from __doc__<br/> 关闭文件<br/> """<br/> close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for<br/> further I/O operations. close() may be called more than once without<br/> error. Some kinds of file objects (for example, opened by popen())<br/> may return an exit status upon closing.<br/> """ def fileno(self): # real signature unknown; restored from __doc__<br/> 文件描述符<br/> """<br/> fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().<br/> """<br/> return 0 def flush(self): # real signature unknown; restored from __doc__<br/> 刷新文件内部缓冲区<br/> """ flush() -> None. Flush the internal I/O buffer. """<br/> pass def isatty(self): # real signature unknown; restored from __doc__<br/> 判断文件是否是同意tty设备<br/> """ isatty() -> true or false. True if the file is connected to a tty device. """<br/> return False def next(self): # real signature unknown; restored from __doc__<br/> 获取下一行数据,不存在,则报错<br/> """ x.next() -> the next value, or raise StopIteration """<br/> pass def read(self, size=None): # real signature unknown; restored from __doc__<br/> 读取指定字节数据<br/> """<br/> read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.<br/> Notice that when in non-blocking mode, less data than what was requested<br/> may be returned, even if no size parameter was given.<br/> """<br/> pass def readinto(self): # real signature unknown; restored from __doc__<br/> 读取到缓冲区,不要用,将被遗弃<br/> """ readinto() -> Undocumented. Don't use this; it may go away. """<br/> pass def readline(self, size=None): # real signature unknown; restored from __doc__<br/> 仅读取一行数据<br/> """<br/> readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum<br/> number of bytes to return (an incomplete line may be returned then).<br/> Return an empty string at EOF.<br/> """<br/> pass def readlines(self, size=None): # real signature unknown; restored from __doc__<br/> 读取所有数据,并根据换行保存值列表<br/> """<br/> readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.<br/> The optional size argument, if given, is an approximate bound on the<br/> total number of bytes in the lines returned.<br/> """<br/> return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__<br/> 指定文件中指针位置<br/> """<br/> seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to<br/> (offset from start of file, offset should be >= 0); other values are 1<br/> (move relative to current position, positive or negative), and 2 (move<br/> relative to end of file, usually negative, although many platforms allow<br/> seeking beyond the end of a file). If the file is opened in text mode,<br/> only offsets returned by tell() are legal. Use of other offsets causes<br/> undefined behavior.<br/> Note that not all file objects are seekable.<br/> """<br/> pass def tell(self): # real signature unknown; restored from __doc__<br/> 获取当前指针位置<br/> """ tell() -> current file position, an integer (may be a long integer). """<br/> pass def truncate(self, size=None): # real signature unknown; restored from __doc__<br/> 截断数据,仅保留指定之前数据<br/> """<br/> truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().<br/> """<br/> pass def write(self, p_str): # real signature unknown; restored from __doc__<br/> 写内容<br/> """<br/> write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before<br/> the file on disk reflects the data written.<br/> """<br/> pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__<br/> 将一个字符串列表写入文件<br/> """<br/> writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object<br/> producing strings. This is equivalent to calling write() for each string.<br/> """<br/> pass def xreadlines(self): # real signature unknown; restored from __doc__<br/> 可用于逐行读取文件,非全部<br/> """<br/> xreadlines() -> returns self. For backward compatibility. File objects now include the performance<br/> optimizations previously implemented in the xreadlines module.<br/> """<br/> pass 2.x
2.x版本
class TextIOWrapper(_TextIOBase):<br/> """<br/> Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be<br/> decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see<br/> help(codecs.Codec) or the documentation for codecs.register) and<br/> defaults to "strict". newline controls how line endings are handled. It can be None, '',<br/> '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is<br/> enabled. Lines in the input can end in '\n', '\r', or '\r\n', and<br/> these are translated into '\n' before being returned to the<br/> caller. If it is '', universal newline mode is enabled, but line<br/> endings are returned to the caller untranslated. If it has any of<br/> the other legal values, input lines are only terminated by the given<br/> string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are<br/> translated to the system default line separator, os.linesep. If<br/> newline is '' or '\n', no translation takes place. If newline is any<br/> of the other legal values, any '\n' characters written are translated<br/> to the given string. If line_buffering is True, a call to flush is implied when a call to<br/> write contains a newline character.<br/> """<br/> def close(self, *args, **kwargs): # real signature unknown<br/> 关闭文件<br/> pass def fileno(self, *args, **kwargs): # real signature unknown<br/> 文件描述符<br/> pass def flush(self, *args, **kwargs): # real signature unknown<br/> 刷新文件内部缓冲区<br/> pass def isatty(self, *args, **kwargs): # real signature unknown<br/> 判断文件是否是同意tty设备<br/> pass def read(self, *args, **kwargs): # real signature unknown<br/> 读取指定字节数据<br/> pass def readable(self, *args, **kwargs): # real signature unknown<br/> 是否可读<br/> pass def readline(self, *args, **kwargs): # real signature unknown<br/> 仅读取一行数据<br/> pass def seek(self, *args, **kwargs): # real signature unknown<br/> 指定文件中指针位置<br/> pass def seekable(self, *args, **kwargs): # real signature unknown<br/> 指针是否可操作<br/> pass def tell(self, *args, **kwargs): # real signature unknown<br/> 获取指针位置<br/> pass def truncate(self, *args, **kwargs): # real signature unknown<br/> 截断数据,仅保留指定之前数据<br/> pass def writable(self, *args, **kwargs): # real signature unknown<br/> 是否可写<br/> pass def write(self, *args, **kwargs): # real signature unknown<br/> 写内容<br/> pass def __getstate__(self, *args, **kwargs): # real signature unknown<br/> pass def __init__(self, *args, **kwargs): # real signature unknown<br/> pass @staticmethod # known case of __new__<br/> def __new__(*args, **kwargs): # real signature unknown<br/> """ Create and return a new object. See help(type) for accurate signature. """<br/> pass def __next__(self, *args, **kwargs): # real signature unknown<br/> """ Implement next(self). """<br/> pass def __repr__(self, *args, **kwargs): # real signature unknown<br/> """ Return repr(self). """<br/> 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 3.x
3.x版本
三:管理上下文
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f: ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2:<br/> pass
可使用此方法对一个文件进行读操作,同时把数据又写入到另一个打开的文件中!
read()、readline() 和 readlines()
每种方法可以接受一个变量以限制每次读取的数据量,但它们通常不使用变量。 .read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。然而 .read() 生成文件内容最直接的字符串表示,但对于连续的面向行的处理,它却是不必要的,并且如果文件大于可用内存,则不可能实现这种处理。
.readline() 和 .readlines() 非常相似。它们都在类似于以下的结构中使用:
fh = open('c:\\autoexec.bat')<br/> for line in fh.readlines():<br/> print line
.readline() 和 .readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for … in … 结构进行处理。另一方面,.readline() 每次只读取一行,通常比 .readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 .readline()。
练习题:用户名与密码的验证
首先新建一个文件,这里为test.log文件,内容为两行如下:
admin$123<br/> ginvip$123456
1:让用户选择1或2,1为登录,2为注册
2:如果用户选择1,用户输入用户名与密码,然后与test.log文件中的用户名与密码进行验证,验证成功输出“登录成功”,否则“登录失败”
3:如果用户选择2,让用户输入用户名与密码,并与test.log文件中的用户名验证,如果test.log中用户名已经存在,则输出“该用户名已经存在”,否则将用户输入的用户与密码以上面test.log文件中的形式写入test.log文件中
def check_user(user) :<br/> with open('test.log','r',encoding='utf-8') as f :<br/> for line in f :<br/> user_list = line.strip()<br/> user_list = user_list.split('$')<br/> if user == user_list[0] :<br/> return True<br/> return False<br/> def register(user,pwd) :<br/> with open('test.log','a',encoding='utf-8') as f :<br/> user_info = '\n' + user + '$' + pwd<br/> if f.write(user_info) :<br/> return True<br/> return False<br/> def login(user,pwd) :<br/> with open('test.log','r',encoding='utf-8') as f :<br/> for line in f:<br/> user_list = line.strip()<br/> user_list = user_list.split('$')<br/> if user == user_list[0] and pwd == user_list[1]:<br/> return True<br/> return False<br/> def main() :<br/> print('welcome to my website')<br/> choice = input('1:login 2:register')<br/> if choice == '':<br/> user = input('input username :')<br/> pwd = input('input password : ')<br/> if check_user(user) :<br/> print('the username is exist')<br/> else:<br/> if register(user,pwd) :<br/> print('register success')<br/> else:<br/> print('register failed')<br/> elif choice == '':<br/> user = input('input username :')<br/> pwd = input('input password : ')<br/> if login(user,pwd) :<br/> print('login success')<br/> else:<br/> print('login failed')<br/> main()
冒泡排序
冒泡排序的原理:
def Bubble_sort(args) :<br/> for i in range(len(args)-1) :<br/> for j in range(len(args) -1):<br/> if args[j] > args[j+1]:<br/> temp = args[j]<br/> args[j] = args[j+1]<br/> args[j+1] = temp<br/> return args<br/> li = [33,2,10,1,9,3,8]<br/> print(Bubble_sort(li))
练习题
1、简述普通参数、指定参数、默认参数、动态参数的区别
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
digit = 0<br/> case = 0<br/> space = 0<br/> other = 0<br/> def func2(s) :<br/> global digit,case,space,other<br/> if not isinstance(s,basestring) :<br/> print('the data type wrong!')<br/> return False<br/> for i in s :<br/> if i.isdigit() :<br/> digit += 1<br/> elif i.isalpha() :<br/> case += 1<br/> elif i.isspace() :<br/> space += 1<br/> else:<br/> other += 1<br/> s = 'I love python , is num 1 , o_k'<br/> a = [1,2,3]<br/> func2(s)<br/> print(digit)<br/> print(case)<br/> print(space)<br/> print(other)<br/> ########################################<br/> 1<br/> 18<br/> 8<br/> 3<br/> 问题:判断是不是字符串后直接退出函数,而不执行下面的代码?
第2题答案
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def func3(v) :<br/> if len(v) > 5 :<br/> return True<br/> else:<br/> return False<br/> a = 'I love python , is num 1 , o_k'<br/> l = [1,2,3]<br/> t = (5,7,9,10,45,10)<br/> print(func3(t))
第三题答案
4、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。
5、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def func5(lis) :<br/> if len(lis) > 2 :<br/> return lis[0:2]<br/> else :<br/> return False<br/> li = [1,2,3]<br/> print(func5(li))<br/> ##########################################<br/> [1, 2]
第五题答案
6、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
def func6(lis) :<br/> new_lis = []<br/> for k in range(len(lis)) :<br/> if k % 2 == 1 :<br/> new_lis.append(lis[k])<br/> return new_lis<br/> li = [1,2,3,8,10,44,77]<br/> tu = ('poe','andy','jet','bruce','jacky')<br/> print(func6(tu))<br/> ##########################################<br/> ['andy', 'bruce']
第六题答案
7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [,,,]} PS:字典中的value只能是字符串或列表
def func7(d) :<br/> v = d.values()<br/> li = []<br/> for i in v :<br/> if len(i) > 2:<br/> li.append(i[0:2])<br/> return li<br/> print(func7(dic))<br/> ##########################################<br/> [[11, 22], 'v1']
第七题答案
8、写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者
def fabonacci(n) :<br/> if n == 0 :<br/> return 0<br/> elif n == 1:<br/> return 1<br/> else:<br/> return fabonacci(n-1) + fabonacci(n-2)<br/> print(fabonacci(10))