Python學習第三天
阿新 • • 發佈:2017-06-18
python
Set集合#是一個無序且不重復的元素集合,只需關註value
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#添加一個元素,如果添加set裏面有的元素將會過濾掉s1 = set()
s1.add(123)
s1.add(123)print(s1)
{123} """
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#差集,兩個集合中不相同的值生成新集合s = set((1,2,3,4))
t = set((1,2,3,4,5))
b = t.difference(s)#返回一個新的set包含t中有但是s中沒有的元素print(b)
{5}
b = s.difference(t)#返回一個新的set包含s中有但是t中沒有的元素print(b)
set() """
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中的所包含在參數集合中的元素s = set((1,2,3))
t = set((1,2,3,4,5))
t.difference_update(s)#返回刪除set “s”中的元素的set “t”print(t)
{4, 5} """ Remove all elements of another set from this set. """
pass
def discard(self, *args, **kwargs): # real signature unknown#移除t = set((1,2,3,4,5))
t.discard(5)#如果在set “t”中存在元素5,則刪除print(t)
{1, 2, 3, 4} """
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#取交集,生成新的集合s = set((1,2,3))
t = set((1,2,3,4,5))
a = s.intersection(t)
b = t.intersection(s)#返回set "s"和 set “t”中共有元素print(a,b)
{1, 2, 3} {1, 2, 3} """
Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.) """
pass
def intersection_update(self, *args, **kwargs): # real signature unknown#取交集,修改原集合s = set((1,2,3))
t = set((1,2,3,4,5))
s.intersection_update(t)#返回只保留含有set “t”中元素的set “s”print(t)
{1, 2, 3, 4, 5} """ Update a set with the intersection of itself and another. """
pass
def isdisjoint(self, *args, **kwargs): # real signature unknown#如果沒有交集,返回Trues1 = set(["alex","eric","tony","fdsf"])
s2 = set(["hjk","fds","alex","tony"])
a = s1.isdisjoint(s2)print(a)
False """ Return True if two sets have a null intersection. """
pass
def issubset(self, *args, **kwargs): # real signature unknown#是否是子集s = set((1,2,3,4))
t = set((1,2,3,4,5))
a = s.issubset(t)#測試是否s中的每一個元素都在t中print(a)
True """ Report whether another set contains this set. """
pass
def issuperset(self, *args, **kwargs): # real signature unknown#是否是父集s = set((1,2,3,4))
t = set((1,2,3,4,5))
a = s.issuperset(t)#測試是否t中的每一個元素都在s中print(a)
False """ Report whether this set contains another set. """
pass
def pop(self, *args, **kwargs): # real signature unknown#刪除任意一個,有返回值s1 = set(["alex","eric","tony","fdsf"])
s2 = set(["hjk","fds","alex","tony"])
a = s2.pop()#隨機刪除一個值,並將刪除的值返回print(a)print(s1,s2)
alex
{‘tony‘, ‘eric‘, ‘fdsf‘, ‘alex‘} {‘tony‘, ‘fds‘, ‘hjk‘} """
Remove and return an arbitrary set element.
Raises KeyError if the set is empty. """
pass
def remove(self, *args, **kwargs): # real signature unknown#刪除指定元素,無返回值s2 = set(["hjk","fds","alex","tony"])
a = s2.remove("hjk")#從set “s2”中刪除指定元素,無返回值;如果不存在則引發keyerrorprint(a)print(s1,s2)
None
{‘tony‘, ‘fds‘, ‘alex‘} """
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#對稱差集(取雙方對象中都不重復的元素),創建新集合s = set((1,2,6))
t = set((1,2,3,4,5))
a = s.symmetric_difference(t)#返回一個新的set包含s和t中不重復的元素print(a)
{3, 4, 5, 6} """
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#差集,改變原來s = set((1,2,3,4))
t = set((1,2,3,4,5))
s.symmetric_difference_update(t)#返回含義set “t”和set “s”中有而不是兩者都有的元素的set “s”print(s)
{5} """ Update a set with the symmetric difference of itself and another. """
pass
def union(self, *args, **kwargs): # real signature unknown#並集s = set((1,2,3,4))
t = set((1,2,3,4,5))
a = s.union(t)#返回一個新的set包含s和t中的每一個元素print(a)
{1, 2, 3, 4, 5} """
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#更新s = set((1,2,3,4))
t = set((1,2,3,4,5))
t.update(s)#“t”中包含“s”中對象,則“t”返回原值s.update(t)#“s”中未包含“t”中對象,則s返回增加t中元素的set“print(t)
{1, 2, 3, 4, 5}print(s)
{1, 2, 3, 4, 5} """ Update a set with the union of itself and others. """
pass
def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __iand__(self, *args, **kwargs): # real signature unknown
""" Return self&=value. """
pass
def __init__(self, seq=()): # known special case of set.__init__
"""
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
# (copied from class doc) """
pass
def __ior__(self, *args, **kwargs): # real signature unknown
""" Return self|=value. """
pass
def __isub__(self, *args, **kwargs): # real signature unknown
""" Return self-=value. """
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __ixor__(self, *args, **kwargs): # real signature unknown
""" Return self^=value. """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
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 __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass
def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass
def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass
def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass
def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass
def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass
__hash__ = None
collections系列
計數器(Counter)#對字典進行加工
class Counter(dict): ‘‘‘Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
>>> c = Counter(‘abcdeabcdabcaba‘) # count elements from a string
>>> c.most_common(3) # three most common elements
[(‘a‘, 5), (‘b‘, 4), (‘c‘, 3)]
>>> sorted(c) # list all unique elements
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]
>>> ‘‘.join(sorted(c.elements())) # list elements with repetitions
‘aaaaabbbbcccdde‘
>>> sum(c.values()) # total of all counts
15
>>> c[‘a‘] # count of letter ‘a‘
5
>>> for elem in ‘shazam‘: # update counts from an iterable
... c[elem] += 1 # by adding 1 to each element‘s count
>>> c[‘a‘] # now there are seven ‘a‘
7
>>> del c[‘b‘] # remove all ‘b‘
>>> c[‘b‘] # now there are zero ‘b‘
0
>>> d = Counter(‘simsalabim‘) # make another counter
>>> c.update(d) # add in the second counter
>>> c[‘a‘] # now there are nine ‘a‘
9
>>> c.clear() # empty the counter
>>> c
Counter()
Note: If a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter(‘aaabbc‘)
>>> c[‘b‘] -= 2 # reduce the count of ‘b‘ by two
>>> c.most_common() # ‘b‘ is still in, but its count is zero
[(‘a‘, 3), (‘c‘, 1), (‘b‘, 0)] ‘‘‘
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6.3
def __init__(*args, **kwds): ‘‘‘Create a new, empty Counter object. And if given, count elements
from an input iterable. Or, initialize the count from another mapping
of elements to their counts.
>>> c = Counter() # a new, empty counter
>>> c = Counter(‘gallahad‘) # a new counter from an iterable
>>> c = Counter({‘a‘: 4, ‘b‘: 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args ‘‘‘
if not args: raise TypeError("descriptor ‘__init__‘ of ‘Counter‘ object "
"needs an argument")
self, *args = args if len(args) > 1: raise TypeError(‘expected at most 1 arguments, got %d‘ % len(args))
super(Counter, self).__init__()
self.update(*args, **kwds) def __missing__(self, key): ‘The count of elements not in the Counter is zero.‘
# Needed so that self[missing_item] does not raise KeyError
return 0 def most_common(self, n=None): ‘‘‘List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter(‘abcdeabcdabcaba‘).most_common(3)
[(‘a‘, 5), (‘b‘, 4), (‘c‘, 3)] ‘‘‘
# Emulate Bag.sortedByCount from Smalltalk
if n is None: return sorted(self.items(), key=_itemgetter(1), reverse=True) return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) def elements(self): ‘‘‘Iterator over elements repeating each as many times as its count.
#列出所有元素
>>> c = Counter(‘ABCABC‘)
>>> sorted(c.elements())
[‘A‘, ‘A‘, ‘B‘, ‘B‘, ‘C‘, ‘C‘]
# Knuth‘s example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product
1836
Note, if an element‘s count has been set to zero or is a negative
number, elements() will ignore it. ‘‘‘
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.items())) # Override dict methods where necessary
@classmethod def fromkeys(cls, iterable, v=None): # There is no equivalent method for counters because setting v=1
# means that no element can have a count greater than one.
raise NotImplementedError( ‘Counter.fromkeys() is undefined. Use Counter(iterable) instead.‘) def update(*args, **kwds):#更新數據>>> a = collections.Counter(["11","22","33"])
a.update(["alex"])>>> print(a)
Counter({‘11‘: 1, ‘33‘: 1, ‘22‘: 1, ‘alex‘: 1}) ‘‘‘Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter(‘which‘)
>>> c.update(‘witch‘) # add elements from another iterable
>>> d = Counter(‘watch‘)
>>> c.update(d) # add elements from another counter
>>> c[‘h‘] # four ‘h‘ in which, witch, and watch
4 ‘‘‘
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn‘t have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
# and outputs are allowed to contain zero and negative counts.
if not args: raise TypeError("descriptor ‘update‘ of ‘Counter‘ object "
"needs an argument")
self, *args = args if len(args) > 1: raise TypeError(‘expected at most 1 arguments, got %d‘ % len(args))
iterable = args[0] if args else None if iterable is not None: if isinstance(iterable, Mapping): if self:
self_get = self.get for elem, count in iterable.items():
self[elem] = count + self_get(elem, 0) else:
super(Counter, self).update(iterable) # fast path when counter is empty
else:
_count_elements(self, iterable) if kwds:
self.update(kwds) def subtract(*args, **kwds):#刪除
‘‘‘Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero. Both the inputs and outputs are
allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter(‘which‘)
>>> c.subtract(‘witch‘) # subtract elements from another iterable
>>> c.subtract(Counter(‘watch‘)) # subtract elements from another counter
>>> c[‘h‘] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c[‘w‘] # 1 in which, minus 1 in witch, minus 1 in watch
-1 ‘‘‘
if not args: raise TypeError("descriptor ‘subtract‘ of ‘Counter‘ object "
"needs an argument")
self, *args = args if len(args) > 1: raise TypeError(‘expected at most 1 arguments, got %d‘ % len(args))
iterable = args[0] if args else None if iterable is not None:
self_get = self.get if isinstance(iterable, Mapping): for elem, count in iterable.items():
self[elem] = self_get(elem, 0) - count else: for elem in iterable:
self[elem] = self_get(elem, 0) - 1 if kwds:
self.subtract(kwds) def copy(self): ‘Return a shallow copy.‘
return self.__class__(self) def __reduce__(self): return self.__class__, (dict(self),) def __delitem__(self, elem): ‘Like dict.__delitem__() but does not raise KeyError for missing values.‘
if elem in self:
super().__delitem__(elem) def __repr__(self): if not self: return ‘%s()‘ % self.__class__.__name__
try:
items = ‘, ‘.join(map(‘%r: %r‘.__mod__, self.most_common())) return ‘%s({%s})‘ % (self.__class__.__name__, items) except TypeError: # handle case where values are not orderable
return ‘{0}({1!r})‘.format(self.__class__.__name__, dict(self)) # Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6.3 exercise 19
# and at http://en.wikipedia.org/wiki/Multiset
# # Outputs guaranteed to only include positive counts.
# # To strip negative and zero counts, add-in an empty counter:
# c += Counter()
def __add__(self, other): ‘‘‘Add counts from two counters.
>>> Counter(‘abbb‘) + Counter(‘bcc‘)
Counter({‘b‘: 4, ‘c‘: 2, ‘a‘: 1}) ‘‘‘
if not isinstance(other, Counter): return NotImplemented
result = Counter() for elem, count in self.items():
newcount = count + other[elem] if newcount > 0:
result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0:
result[elem] = count return result def __sub__(self, other): ‘‘‘ Subtract count, but keep only results with positive counts.
>>> Counter(‘abbbc‘) - Counter(‘bccd‘)
Counter({‘b‘: 2, ‘a‘: 1}) ‘‘‘
if not isinstance(other, Counter): return NotImplemented
result = Counter() for elem, count in self.items():
newcount = count - other[elem] if newcount > 0:
result[elem] = newcount for elem, count in other.items(): if elem not in self and count < 0:
result[elem] = 0 - count return result def __or__(self, other): ‘‘‘Union is the maximum of value in either of the input counters.
>>> Counter(‘abbb‘) | Counter(‘bcc‘)
Counter({‘b‘: 3, ‘c‘: 2, ‘a‘: 1}) ‘‘‘
if not isinstance(other, Counter): return NotImplemented
result = Counter() for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count if newcount > 0:
result[elem] = newcount for elem, count in other.items(): if elem not in self and count > 0:
result[elem] = count return result def __and__(self, other): ‘‘‘ Intersection is the minimum of corresponding counts.
>>> Counter(‘abbb‘) & Counter(‘bcc‘)
Counter({‘b‘: 1}) ‘‘‘
if not isinstance(other, Counter): return NotImplemented
result = Counter() for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count if newcount > 0:
result[elem] = newcount return result def __pos__(self): ‘Adds an empty counter, effectively stripping negative and zero counts‘
result = Counter() for elem, count in self.items(): if count > 0:
result[elem] = count return result def __neg__(self): ‘‘‘Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts. ‘‘‘
result = Counter() for elem, count in self.items(): if count < 0:
result[elem] = 0 - count return result def _keep_positive(self): ‘‘‘Internal method to strip elements with a negative or zero count‘‘‘
nonpositive = [elem for elem, count in self.items() if not count > 0] for elem in nonpositive: del self[elem] return self def __iadd__(self, other): ‘‘‘Inplace add from another counter, keeping only positive counts.
>>> c = Counter(‘abbb‘)
>>> c += Counter(‘bcc‘)
>>> c
Counter({‘b‘: 4, ‘c‘: 2, ‘a‘: 1}) ‘‘‘
for elem, count in other.items():
self[elem] += count return self._keep_positive() def __isub__(self, other): ‘‘‘Inplace subtract counter, but keep only results with positive counts.
>>> c = Counter(‘abbbc‘)
>>> c -= Counter(‘bccd‘)
>>> c
Counter({‘b‘: 2, ‘a‘: 1}) ‘‘‘
for elem, count in other.items():
self[elem] -= count return self._keep_positive() def __ior__(self, other): ‘‘‘Inplace union is the maximum of value from either counter.
>>> c = Counter(‘abbb‘)
>>> c |= Counter(‘bcc‘)
>>> c
Counter({‘b‘: 3, ‘c‘: 2, ‘a‘: 1}) ‘‘‘
for elem, other_count in other.items():
count = self[elem] if other_count > count:
self[elem] = other_count return self._keep_positive() def __iand__(self, other): ‘‘‘Inplace intersection is the minimum of corresponding counts.
>>> c = Counter(‘abbb‘)
>>> c &= Counter(‘bcc‘)
>>> c
Counter({‘b‘: 1}) ‘‘‘
for elem, count in self.items():
other_count = other[elem] if other_count < count:
self[elem] = other_count return self._keep_positive()
有序字典(OrderedDict)
class OrderedDict(dict): """ Dictionary that remembers insertion order """
def clear(self): # real signature unknown; restored from __doc__
""" od.clear() -> None. Remove all items from od. """
pass
def copy(self): # real signature unknown; restored from __doc__
""" od.copy() -> a shallow copy of od """
pass
@classmethod def fromkeys(cls, S, v=None): # real signature unknown; restored from __doc__
"""
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None. """
pass
def items(self, *args, **kwargs): # real signature unknown
pass
def keys(self, *args, **kwargs): # real signature unknown
pass
def move_to_end(self, *args, **kwargs): # real signature unknown#指定一個值放到最後
"""
Move an existing element to the end (or beginning if last==False).
Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key). """
pass
def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
od.pop(k[,d]) -> v, remove specified key and return the corresponding
value. If key is not found, d is returned if given, otherwise KeyError
is raised. """
pass
def popitem(self): # real signature unknown; restored from __doc__
"""
od.popitem() -> (k, v), return and remove a (key, value) pair.
Pairs are returned in LIFO order if last is true or FIFO order if false. """
pass
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od """
pass
def update(self, *args, **kwargs): # real signature unknown
pass
def values(self, *args, **kwargs): # real signature unknown
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
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 __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __reversed__(self): # real signature unknown; restored from __doc__
""" od.__reversed__() <==> reversed(od) """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
pass
__dict__ = None # (!) real value is ‘‘
__hash__ = None
默認字典(defaultdict)
#!/usr/bin/env python3import collections
li = [11,22,33,44,55,66,77,88,99]
my_dict = collections.defaultdict(list)#通過默認字典,設置my_dict為空列表for i in li: if i >66:
my_dict["k1"].append(i) else:
my_dict["k2"].append(i)print(my_dict["k1"],my_dict["k2"])
[77, 88, 99] [11, 22, 33, 44, 55, 66]
可命名元組(namedtuple)
#!/usr/bin/env python3import collections
MytupleClass = collections.namedtuple("MytupleClass",["x","y","z"])#通過自定義類創建別名a = MytupleClass(11,22,33)#通過自定義類給定元素賦值給“a”print(a.x,a.y,a.z)#打印出對應別名的值11 22 33
雙向隊列(deque)
class deque(object): """
deque([iterable[, maxlen]]) --> deque object
A list-like sequence optimized for data accesses near its endpoints. """
def append(self, *args, **kwargs): # real signature unknown#添加元素
""" Add an element to the right side of the deque. """
pass
def appendleft(self, *args, **kwargs): # real signature unknown#在左邊添加元素
""" Add an element to the left side of the deque. """
pass
def clear(self, *args, **kwargs): # real signature unknown#清空元素
""" Remove all elements from the deque. """
pass
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a deque. """
pass
def count(self, value): # real signature unknown; restored from __doc__#統計元素出現的次數
""" D.count(value) -> integer -- return number of occurrences of value """
return 0 def extend(self, *args, **kwargs): # real signature unknown#擴展(添加多個數據)
""" Extend the right side of the deque with elements from the iterable """
pass
def extendleft(self, *args, **kwargs): # real signature unknown#在左邊擴展(添加多個數據)
""" Extend the left side of the deque with elements from the iterable """
pass
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__#索引
"""
D.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present. """
return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__#插入
""" D.insert(index, object) -- insert object before index """
pass
def pop(self, *args, **kwargs): # real signature unknown#移除並拿到
""" Remove and return the rightmost element. """
pass
def popleft(self, *args, **kwargs): # real signature unknown#從左邊移除並拿到
""" Remove and return the leftmost element. """
pass
def remove(self, value): # real signature unknown; restored from __doc__#刪除指定值
""" D.remove(value) -- remove first occurrence of value. """
pass
def reverse(self): # real signature unknown; restored from __doc__#反轉
""" D.reverse() -- reverse *IN PLACE* """
pass
def rotate(self, *args, **kwargs): # real signature unknown#旋轉d = collections.deque(["1","10","1","a","f","dg"])print(d)
d.rotate(3)#按照數字進行旋轉,每次拿最後一個元素放到最前面print(d)
deque([‘1‘, ‘10‘, ‘1‘, ‘a‘, ‘f‘, ‘dg‘])
deque([‘a‘, ‘f‘, ‘dg‘, ‘1‘, ‘10‘, ‘1‘]) """ Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __bool__(self, *args, **kwargs): # real signature unknown
""" self != 0 """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __copy__(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a deque. """
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __iadd__(self, *args, **kwargs): # real signature unknown
""" Implement self+=value. """
pass
def __imul__(self, *args, **kwargs): # real signature unknown
""" Implement self*=value. """
pass
def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
"""
deque([iterable[, maxlen]]) --> deque object
A list-like sequence optimized for data accesses near its endpoints.
# (copied from class doc) """
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
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 __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __reversed__(self): # real signature unknown; restored from __doc__
""" D.__reversed__() -- return a reverse iterator over the deque """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -- size of D in memory, in bytes """
pass
maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""maximum size of a deque or None if unbounded"""
__hash__ = None
單向隊列
#!/usr/bin/env python3import queue
q = queue.Queue()#單向隊列q.put("123","fds")#添加一條q.put("45")#添加一條print(q.qsize())#統計隊列中有多少數據print(q.get())#取出一條數據(采用先進先出原則)
class Queue: ‘‘‘Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite. ‘‘‘
def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize) # mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
# is shared between the three conditions, so acquiring and
# releasing the conditions also acquires and releases mutex.
self.mutex = threading.Lock() # Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = threading.Condition(self.mutex) # Notify not_full whenever an item is removed from the queue;
# a thread waiting to put is notified then.
self.not_full = threading.Condition(self.mutex) # Notify all_tasks_done whenever the number of unfinished tasks
# drops to zero; thread waiting to join() is notified to resume
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0 def task_done(self): ‘‘‘Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue. ‘‘‘
with self.all_tasks_done:
unfinished = self.unfinished_tasks - 1 if unfinished <= 0: if unfinished < 0: raise ValueError(‘task_done() called too many times‘)
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished def join(self): ‘‘‘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
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks. ‘‘‘
with self.all_tasks_done: while self.unfinished_tasks:
self.all_tasks_done.wait() def qsize(self):#查看隊列中元素的個數
‘‘‘Return the approximate size of the queue (not reliable!).‘‘‘
with self.mutex: return self._qsize() def empty(self):#和clear一樣
‘‘‘Return True if the queue is empty, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() == 0
as a direct substitute, but be aware that either approach risks a race
condition where a queue can grow before the result of empty() or
qsize() can be used.
To create code that needs to wait for all queued tasks to be
completed, the preferred technique is to use the join() method. ‘‘‘
with self.mutex: return not self._qsize() def full(self):#是否填滿
‘‘‘Return True if the queue is full, False otherwise (not reliable!).
This method is likely to be removed at some point. Use qsize() >= n
as a direct substitute, but be aware that either approach risks a race
condition where a queue can shrink before the result of full() or
qsize() can be used. ‘‘‘
with self.mutex: return 0 < self.maxsize <= self._qsize() def put(self, item, block=True, timeout=None):#插入數據
‘‘‘Put an item into the queue.
If optional args ‘block‘ is true and ‘timeout‘ is None (the default),
block if necessary until a free slot is available. If ‘timeout‘ is
a non-negative number, it blocks at most ‘timeout‘ seconds and raises
the Full exception if no free slot was available within that time.
Otherwise (‘block‘ is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception (‘timeout‘
is ignored in that case). ‘‘‘
with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize:
self.not_full.wait() elif timeout < 0: raise ValueError("‘timeout‘ must be a non-negative number") else:
endtime = time() + timeout while self._qsize() >= self.maxsize:
remaining = endtime - time() if remaining <= 0.0: raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify() def get(self, block=True, timeout=None):#取數據
‘‘‘Remove and return an item from the queue.
If optional args ‘block‘ is true and ‘timeout‘ is None (the default),
block if necessary until an item is available. If ‘timeout‘ is
a non-negative number, it blocks at most ‘timeout‘ seconds and raises
the Empty exception if no item was available within that time.
Otherwise (‘block‘ is false), return an item if one is immediately
available, else raise the Empty exception (‘timeout‘ is ignored
in that case). ‘‘‘
with self.not_empty: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize():
self.not_empty.wait() elif timeout < 0: raise ValueError("‘timeout‘ must be a non-negative number") else:
endtime = time() + timeout while not self._qsize():
remaining = endtime - time() if remaining <= 0.0: raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify() return item def put_nowait(self, item): ‘‘‘Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available.
Otherwise raise the Full exception. ‘‘‘
return self.put(item, block=False) def get_nowait(self): ‘‘‘Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise
raise the Empty exception. ‘‘‘
return self.get(block=False) # Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque() def _qsize(self): return len(self.queue) # Put a new item in the queue
def _put(self, item):
self.queue.append(item) # Get an item from the queue
def _get(self): return self.queue.popleft()
淺拷貝
dic = {"cpu":[80],"mom":[80],"disk":[80]}print("old",dic)
new_dic = copy.copy(dic) #淺拷貝,會改變原數據new_dic["cpu"][0] = 50print(dic)print(new_dic)
深拷貝
dic = {"cpu":80,"mom":80,"disk":80}print("old",dic)
new_dic = copy.deepcopy(dic)#深拷貝則修改你要改的值new_dic["cpu"] = 50print(dic)print(new_dic)
函數
def show():#def是定義函數的關鍵字,函數名後必須更括號
print("123") return"ss" #返回值,不寫return返回Nonea = show()#函數名加擴號,表示執行該函數,可將返回值賦值給變量print(a)123ss#一個參數def show(a):#形參
print(a)
show(123)#實參,把參數賦值給a123#多個參數def show(a,b,c):#可指定多形參
print(a,b,c)
show(123,456,789)#實參數量必須和形參一致(一一對應)123 456 789def show(args): print(args)
show([123,456,789])
[123, 456, 789]#默認參數def show(a,b=123):#默認參數須先賦值,只能寫到最後(a後面,並且後面也不能跟形參)
print(a,b)
show(123,456)123 456#指定參數def show(a,b,c): print(a,b,c)
show(c=789,a=123,b=456,)123 456 789#動態參數def show(*args):#單星轉成元組
print(args,type(args))
show([123,456,789])
([123, 456, 789],) <class ‘tuple‘>def show(**kwargs):#雙星轉成字典
print(kwargs,type(kwargs))
show(a=123,b=456)
{‘b‘: 456, ‘a‘: 123} <class ‘dict‘>def show(*a,**b):#混合模式下,必須單星在前
print(a,type(a)) print(b,type(b))
show(123,456,abc = 123,cde = 456)#不能混傳,如(abc = 123,123)必須根據星來使用(123, 456) <class ‘tuple‘>{‘cde‘: 456, ‘abc‘: 123} <class ‘dict‘>def show(*a,**b): print(a,type(a)) print(b,type(b))
l =(123,456)
d ={‘abc‘:123,‘cde‘:456}
show(*l,**d)#把值傳到指定位置(123, 456) <class ‘tuple‘>{‘abc‘: 123, ‘cde‘: 456} <class ‘dict‘>#字符格式化c = ["name","abc"]
d = {"a":"name","b":"abc"}
s = "{0} is {1}".format(*c)
s1 = "{a} is {b}".format(**d)print(s,s1)
Lambda表達式
def func(a,b): return a*b
ret = func(4,5)print(ret)#lambda表達式,同以上函數func = lambda a,b: a*b
ret = func(4,5)print(ret)
內置函數#只寫了部分
all()#傳入的序列所有的值都真,才為真all(["",[],(),{},None])#為假any()#只有一個真都為真any(["",[],(),{},None,1,])#只有一個真都為真ascii(8) 等同 (int.__repr__(8))
bin()#二進制bytearray("方法",encoding="utf-8")#轉成字節數組bytes("方法",encoding="utf-8")#轉成字符callable()#是否可執行chr()#數字轉ascii字符chr(65)
ord()#ascii轉數字ord("A")
enumerate()#生成序列li = ["a","b","c"]for i,item in enumerate(li,1): print(i,item)
eval("6*8")#將字符串運算轉換為數字運算
文件操作
文件句柄 = 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
Python學習第三天