1、计数器(counter)

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

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

如:

= collections.Counter('abcdeabcdabcaba')

print c

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

参数里可以是列表或者远足也可以

counter原代码:

########################################################################
###  Counter
########################################################################class Counter(dict):'''Dict subclass for counting hashable items.  Sometimes called a bagor multiset.  Elements are stored as dictionary keys and their countsare 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>>> c['a']                          # count of letter 'a'>>> 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'>>> del c['b']                      # remove all 'b'>>> c['b']                          # now there are zero 'b'>>> d = Counter('simsalabim')       # make another counter>>> c.update(d)                     # add in the second counter>>> c['a']                          # now there are nine 'a'>>> c.clear()                       # empty the counter>>> cCounter()Note:  If a count is set to zero or reduced to zero, it will remainin 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.3def __init__(self, iterable=None, **kwds):'''Create a new, empty Counter object.  And if given, count elementsfrom an input iterable.  Or, initialize the count from another mappingof 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'''super(Counter, self).__init__()self.update(iterable, **kwds)def __missing__(self, key):""" 对于不存在的元素,返回计数器为0 """'The count of elements not in the Counter is zero.'# Needed so that self[missing_item] does not raise KeyErrorreturn 0def most_common(self, n=None):""" 数量从大到写排列,获取前N个元素 """'''List the n most common elements and their counts from the mostcommon 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 Smalltalkif n is None:return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)return _heapq.nlargest(n, self.iteritems(), 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>>> productNote, if an element's count has been set to zero or is a negativenumber, elements() will ignore it.'''# Emulate Bag.do from Smalltalk and Multiset.begin from C++.return _chain.from_iterable(_starmap(_repeat, self.iteritems()))# Override dict methods where necessary
@classmethoddef 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(self, iterable=None, **kwds):""" 更新计数器,其实就是增加;如果原来没有,则新建,如果有则加一 """'''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'''# 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 iterable is not None:if isinstance(iterable, Mapping):if self:self_get = self.getfor elem, count in iterable.iteritems():self[elem] = self_get(elem, 0) + countelse:super(Counter, self).update(iterable) # fast path when counter is emptyelse:self_get = self.getfor elem in iterable:self[elem] = self_get(elem, 0) + 1if kwds:self.update(kwds)def subtract(self, iterable=None, **kwds):""" 相减,原来的计数器中的每一个元素的数量减去后添加的元素的数量 """'''Like dict.update() but subtracts counts instead of replacing them.Counts can be reduced below zero.  Both the inputs and outputs areallowed 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>>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch-1'''if iterable is not None:self_get = self.getif isinstance(iterable, Mapping):for elem, count in iterable.items():self[elem] = self_get(elem, 0) - countelse:for elem in iterable:self[elem] = self_get(elem, 0) - 1if 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(Counter, self).__delitem__(elem)def __repr__(self):if not self:return '%s()' % self.__class__.__name__items = ', '.join(map('%r: %r'.__mod__, self.most_common()))return '%s({%s})' % (self.__class__.__name__, items)# 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 NotImplementedresult = Counter()for elem, count in self.items():newcount = count + other[elem]if newcount > 0:result[elem] = newcountfor elem, count in other.items():if elem not in self and count > 0:result[elem] = countreturn resultdef __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 NotImplementedresult = Counter()for elem, count in self.items():newcount = count - other[elem]if newcount > 0:result[elem] = newcountfor elem, count in other.items():if elem not in self and count < 0:result[elem] = 0 - countreturn resultdef __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 NotImplementedresult = Counter()for elem, count in self.items():other_count = other[elem]newcount = other_count if count < other_count else countif newcount > 0:result[elem] = newcountfor elem, count in other.items():if elem not in self and count > 0:result[elem] = countreturn resultdef __and__(self, other):''' Intersection is the minimum of corresponding counts.>>> Counter('abbb') & Counter('bcc')Counter({'b': 1})'''if not isinstance(other, Counter):return NotImplementedresult = Counter()for elem, count in self.items():other_count = other[elem]newcount = count if count < other_count else other_countif newcount > 0:result[elem] = newcountreturn resultCounter

View Code

2、有序字典(orderedDict )

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

class OrderedDict(dict):'Dictionary that remembers insertion order'# An inherited dict maps keys to values.# The inherited dict provides __getitem__, __len__, __contains__, and get.# The remaining methods are order-aware.# Big-O running times for all methods are the same as regular dictionaries.# The internal self.__map dict maps keys to links in a doubly linked list.# The circular doubly linked list starts and ends with a sentinel element.# The sentinel element never gets deleted (this simplifies the algorithm).# Each link is stored as a list of length three:  [PREV, NEXT, KEY].def __init__(self, *args, **kwds):'''Initialize an ordered dictionary.  The signature is the same asregular dictionaries, but keyword arguments are not recommended becausetheir insertion order is arbitrary.'''if len(args) > 1:raise TypeError('expected at most 1 arguments, got %d' % len(args))try:self.__rootexcept AttributeError:self.__root = root = []                     # sentinel noderoot[:] = [root, root, None]self.__map = {}self.__update(*args, **kwds)def __setitem__(self, key, value, dict_setitem=dict.__setitem__):'od.__setitem__(i, y) <==> od[i]=y'# Setting a new item creates a new link at the end of the linked list,# and the inherited dictionary is updated with the new key/value pair.if key not in self:root = self.__rootlast = root[0]last[1] = root[0] = self.__map[key] = [last, root, key]return dict_setitem(self, key, value)def __delitem__(self, key, dict_delitem=dict.__delitem__):'od.__delitem__(y) <==> del od[y]'# Deleting an existing item uses self.__map to find the link which gets# removed by updating the links in the predecessor and successor nodes.
        dict_delitem(self, key)link_prev, link_next, _ = self.__map.pop(key)link_prev[1] = link_next                        # update link_prev[NEXT]link_next[0] = link_prev                        # update link_next[PREV]def __iter__(self):'od.__iter__() <==> iter(od)'# Traverse the linked list in order.root = self.__rootcurr = root[1]                                  # start at the first nodewhile curr is not root:yield curr[2]                               # yield the curr[KEY]curr = curr[1]                              # move to next nodedef __reversed__(self):'od.__reversed__() <==> reversed(od)'# Traverse the linked list in reverse order.root = self.__rootcurr = root[0]                                  # start at the last nodewhile curr is not root:yield curr[2]                               # yield the curr[KEY]curr = curr[0]                              # move to previous nodedef clear(self):'od.clear() -> None.  Remove all items from od.'root = self.__rootroot[:] = [root, root, None]self.__map.clear()dict.clear(self)# -- the following methods do not depend on the internal structure --def keys(self):'od.keys() -> list of keys in od'return list(self)def values(self):'od.values() -> list of values in od'return [self[key] for key in self]def items(self):'od.items() -> list of (key, value) pairs in od'return [(key, self[key]) for key in self]def iterkeys(self):'od.iterkeys() -> an iterator over the keys in od'return iter(self)def itervalues(self):'od.itervalues -> an iterator over the values in od'for k in self:yield self[k]def iteritems(self):'od.iteritems -> an iterator over the (key, value) pairs in od'for k in self:yield (k, self[k])update = MutableMapping.update__update = update # let subclasses override update without breaking __init____marker = object()def pop(self, key, default=__marker):'''od.pop(k[,d]) -> v, remove specified key and return the correspondingvalue.  If key is not found, d is returned if given, otherwise KeyErroris raised.'''if key in self:result = self[key]del self[key]return resultif default is self.__marker:raise KeyError(key)return defaultdef setdefault(self, key, default=None):'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'if key in self:return self[key]self[key] = defaultreturn defaultdef popitem(self, last=True):'''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.'''if not self:raise KeyError('dictionary is empty')key = next(reversed(self) if last else iter(self))value = self.pop(key)return key, valuedef __repr__(self, _repr_running={}):'od.__repr__() <==> repr(od)'call_key = id(self), _get_ident()if call_key in _repr_running:return '...'_repr_running[call_key] = 1try:if not self:return '%s()' % (self.__class__.__name__,)return '%s(%r)' % (self.__class__.__name__, self.items())finally:del _repr_running[call_key]def __reduce__(self):'Return state information for pickling'items = [[k, self[k]] for k in self]inst_dict = vars(self).copy()for k in vars(OrderedDict()):inst_dict.pop(k, None)if inst_dict:return (self.__class__, (items,), inst_dict)return self.__class__, (items,)def copy(self):'od.copy() -> a shallow copy of od'return self.__class__(self)@classmethoddef fromkeys(cls, iterable, value=None):'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.If not specified, the value defaults to None.'''self = cls()for key in iterable:self[key] = valuereturn selfdef __eq__(self, other):'''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitivewhile comparison to a regular mapping is order-insensitive.'''if isinstance(other, OrderedDict):return dict.__eq__(self, other) and all(_imap(_eq, self, other))return dict.__eq__(self, other)def __ne__(self, other):'od.__ne__(y) <==> od!=y'return not self == other# -- the following methods support python 3.x style dictionary views --def viewkeys(self):"od.viewkeys() -> a set-like object providing a view on od's keys"return KeysView(self)def viewvalues(self):"od.viewvalues() -> an object providing a view on od's values"return ValuesView(self)def viewitems(self):"od.viewitems() -> a set-like object providing a view on od's items"return ItemsView(self)OrderedDict

View Code

3、默认字典(defaultdict)

defaultdict是对字典的类型的补充,他默认给字典的值设置了一个类型。

4、可命名元组(namedtuple)

根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。

mytuple = collections.namedtuple('mytuple',['x','y','z'])

new = mytuple(1,2,3)

print new

结果:mytuple(x=1, y=2, z=3)

可得出可命名元组,调用时: new.x  , 结果: 1一般运用在坐标上

5、双向队列(deque)

一个线程安全的双向队列

q = collections.deque()

q.append(1)

q.append(2)

print q

结果:deque([1,2])

q.pop() 结果:2 从右起把2取走

q.popleft()  从左起把1取走

class deque(object):"""deque([iterable[, maxlen]]) --> deque objectBuild an ordered collection with optimized access from its endpoints."""def append(self, *args, **kwargs): # real signature unknown""" Add an element to the right side of the deque. """passdef appendleft(self, *args, **kwargs): # real signature unknown""" Add an element to the left side of the deque. """passdef clear(self, *args, **kwargs): # real signature unknown""" Remove all elements from the deque. """passdef count(self, value): # real signature unknown; restored from __doc__""" D.count(value) -> integer -- return number of occurrences of value """return 0def extend(self, *args, **kwargs): # real signature unknown""" Extend the right side of the deque with elements from the iterable """passdef extendleft(self, *args, **kwargs): # real signature unknown""" Extend the left side of the deque with elements from the iterable """passdef pop(self, *args, **kwargs): # real signature unknown""" Remove and return the rightmost element. """passdef popleft(self, *args, **kwargs): # real signature unknown""" Remove and return the leftmost element. """passdef remove(self, value): # real signature unknown; restored from __doc__""" D.remove(value) -- remove first occurrence of value. """passdef reverse(self): # real signature unknown; restored from __doc__""" D.reverse() -- reverse *IN PLACE* """passdef rotate(self, *args, **kwargs): # real signature unknown""" Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """passdef __copy__(self, *args, **kwargs): # real signature unknown""" Return a shallow copy of a deque. """passdef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <==> del x[y] """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <==> x==y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__('name') <==> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <==> x[y] """passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <==> x>=y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <==> x>y """passdef __iadd__(self, y): # real signature unknown; restored from __doc__""" x.__iadd__(y) <==> x+=y """passdef __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__"""deque([iterable[, maxlen]]) --> deque objectBuild an ordered collection with optimized access from its endpoints.# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <==> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <==> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <==> x<=y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <==> x<y """pass@staticmethod # known case of __new__def __new__(S, *more): # real signature unknown; restored from __doc__""" T.__new__(S, ...) -> a new object with type S, a subtype of T """passdef __ne__(self, y): # real signature unknown; restored from __doc__""" x.__ne__(y) <==> x!=y """passdef __reduce__(self, *args, **kwargs): # real signature unknown""" Return state information for pickling. """passdef __repr__(self): # real signature unknown; restored from __doc__""" x.__repr__() <==> repr(x) """passdef __reversed__(self): # real signature unknown; restored from __doc__""" D.__reversed__() -- return a reverse iterator over the deque """passdef __setitem__(self, i, y): # real signature unknown; restored from __doc__""" x.__setitem__(i, y) <==> x[i]=y """passdef __sizeof__(self): # real signature unknown; restored from __doc__""" D.__sizeof__() -- size of D in memory, in bytes """passmaxlen = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default"""maximum size of a deque or None if unbounded"""__hash__ = Nonedeque

View Code

注:既然有双向队列,也有单项队列(先进先出 FIFO ) 使用的是Queue模块,源代码如下:

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 = maxsizeself._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 resumeself.all_tasks_done = _threading.Condition(self.mutex)self.unfinished_tasks = 0def 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 processingon the task is complete.If a join() is currently blocking, it will resume when all itemshave been processed (meaning that a task_done() call was receivedfor every item that had been put() into the queue).Raises a ValueError if called more times than there were itemsplaced in the queue."""self.all_tasks_done.acquire()try:unfinished = self.unfinished_tasks - 1if unfinished <= 0:if unfinished < 0:raise ValueError('task_done() called too many times')self.all_tasks_done.notify_all()self.unfinished_tasks = unfinishedfinally:self.all_tasks_done.release()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 thequeue. 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."""self.all_tasks_done.acquire()try:while self.unfinished_tasks:self.all_tasks_done.wait()finally:self.all_tasks_done.release()def qsize(self):"""Return the approximate size of the queue (not reliable!)."""self.mutex.acquire()n = self._qsize()self.mutex.release()return ndef empty(self):"""Return True if the queue is empty, False otherwise (not reliable!)."""self.mutex.acquire()n = not self._qsize()self.mutex.release()return ndef full(self):"""Return True if the queue is full, False otherwise (not reliable!)."""self.mutex.acquire()n = 0 < self.maxsize == self._qsize()self.mutex.release()return ndef 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' isa non-negative number, it blocks at most 'timeout' seconds and raisesthe Full exception if no free slot was available within that time.Otherwise ('block' is false), put an item on the queue if a free slotis immediately available, else raise the Full exception ('timeout'is ignored in that case)."""self.not_full.acquire()try:if self.maxsize > 0:if not block:if self._qsize() == self.maxsize:raise Fullelif 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() + timeoutwhile self._qsize() == self.maxsize:remaining = endtime - _time()if remaining <= 0.0:raise Fullself.not_full.wait(remaining)self._put(item)self.unfinished_tasks += 1self.not_empty.notify()finally:self.not_full.release()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, False)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' isa non-negative number, it blocks at most 'timeout' seconds and raisesthe Empty exception if no item was available within that time.Otherwise ('block' is false), return an item if one is immediatelyavailable, else raise the Empty exception ('timeout' is ignoredin that case)."""self.not_empty.acquire()try:if not block:if not self._qsize():raise Emptyelif 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() + timeoutwhile not self._qsize():remaining = endtime - _time()if remaining <= 0.0:raise Emptyself.not_empty.wait(remaining)item = self._get()self.not_full.notify()return itemfinally:self.not_empty.release()def get_nowait(self):"""Remove and return an item from the queue without blocking.Only get an item if one is immediately available. Otherwiseraise the Empty exception."""return self.get(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 representationdef _init(self, maxsize):self.queue = deque()def _qsize(self, len=len):return len(self.queue)# Put a new item in the queuedef _put(self, item):self.queue.append(item)# Get an item from the queuedef _get(self):return self.queue.popleft()Queue.Queue

View Code

说到队列,再提下其和栈的区别:

队列:FIFO(先进先出)

栈:后进先出

转载于:https://www.cnblogs.com/fengzaoye/p/5709559.html

python基础_collections系列相关推荐

  1. 【Python基础入门系列】第01天:环境搭建

    其实 Python 已经是一个很老的编程语言了,到现在(2019年) Python 已经高龄 28 岁,比很多程序员的年龄都大.现在之所以这么流行和社区.人工智能的发展,有很大的关系. 千里之行始于足 ...

  2. 【Python基础入门系列】第10天:Python 类与对象

    首先,我已经假定你是个萌新或已经看了无数遍的垃圾文章,然后依然搞不懂类和对象,但是呢起码知道有类和对象这么两个玩意儿,我觉得有必要找一篇生动形象的示例来讲解. 由于你可能没有编程经验, 所以无法从学过 ...

  3. 【Python基础入门系列】第07天:Python 数据结构--序列

    python内置序列类型最常见的是列表,元组和字符串.(序列是python中最基础的数据结构,而数据结构是计算机存储,组织数据的方式.) 另外还提供了字典和集合的数据结构,但他们属于无顺序的数据集合体 ...

  4. 【Python基础入门系列】第05天:Python函数

    前面我们写过九九乘法表,但如果我要七七乘法表或五五乘法表的话,你会看到三者代码极其类似,只是循环变量不同,那么如何做到代码重用,而不是简单拷贝黏贴修改呢,其实可是使用函数完成这一功能! 先来试着看一看 ...

  5. 【Python基础入门系列】第04天:Python 流程控制

    在编程的世界中,流程控制是程序员运行的基础,流程控制决定了程序按照什么样的方式去执行,本节给大家介绍 Python 流程控制相关语法. if 语句 if 语句表示如何发生什么样的条件,执行什么样的逻辑 ...

  6. 【Python基础入门系列】第02天:Python 基础语法

    Python 语言与 Perl,C 和 Java 等语言有许多相似之处.但是,也存在一些差异.在本章中我们将来学习 Python 的基础语法,让你快速学会Python 编程. 开始你的第一个 Pyth ...

  7. Python基础教学系列— 基础语法

    标识符 所谓的标识符就是对变量.常量.函数.类等对象起的名字. 首先必须说明的是,Python语言在任何场景都严格区分大小写!也就是说A和a代表的意义完全不同 python对于表示标识符的命名有如下规 ...

  8. 【Python基础入门系列】第09天:Python tuple

    Python 中的数据结构是通过某种方式组织在一起的数据元素的集合,这些数据元素可以是数字.字符.甚至可以是其他数据结构 在 Python 中,最基本的数据结构是序列(在前面文章我们也说过序列),序列 ...

  9. 【Python基础入门系列】第08天:Python List

    Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素. LIST   列表 比如,列出班里所有同学的名字,就可以用一个list表示: >> ...

最新文章

  1. jenkins2 multibranch
  2. 解决Multiple dex files define Lcom/qq/e/ads/ADActivity;
  3. ios中利用NSDateComponents、NSDate、NSCalendar判断当前时间是否在一天的某个时间段内。...
  4. java 32位授权码_Java实现OAuth2.0授权码方式
  5. C#通过属性名字符串获取、设置对象属性值
  6. Jenkins-安装jenkins2.7.1版本
  7. IplImage 应用解读
  8. 【网络学习】Coverity代码检查工具详细介绍
  9. 佳能2900打印机与win10不兼容_lbp2900+驱动下载
  10. 新版qq虚拟摄像头颜色不正常_分享 | 在线教学常见问题QQ直播、视频通话、群课堂...
  11. 【Docker之Swarm详细讲解Swarm集群搭建管理节点工作节点Raft一致性协议overlay网络Docker结合Swarm部署WordPress个人博客实战】
  12. android 全屏广告,手机端全屏广告展示问题
  13. c执行cmd pdf2swf_SWFTOOLS PDF2SWF 参数详解
  14. 软考成绩什么时候出?
  15. spss之“方差分析”
  16. matlap心形代码+二维画图
  17. 使用Windows NT 的安全性(转)
  18. 医疗项目的一个讲解(医疗项目)搜索模块 药品添加模块 订单生成 注册模块 支付模块
  19. html静态网站基于HTML+CSS+JavaScript上海美食介绍网站网页设计与实现共计5个页面
  20. python:jinja2 模板 实例

热门文章

  1. 全国计算机考试网页制作,全国计算机信息高新技术考试网页制作(FrontPage平台)网页制作员级考试考试大纲...
  2. java 分析数据类型_Java数据类型分析
  3. 华为7c手机怎么恢复出厂设置_华为手机越用越卡,恢复出厂设置真有用?别乱来,看完就明白了!...
  4. linux如何杀死ping进程,linux下ping命令使用详解
  5. Linux命令发送Http请求
  6. Spring依赖注入static静态变量相关问题
  7. c语言编写程序统计某给定ascii文件中个字母的出现频率,2016年浙江理工大学理学院C语言程序设计考研复试题库...
  8. lstrip在python中是什么意思_为什么氦气吸入后会变声?
  9. 1008 数组元素右移k位
  10. 初始化列表和构造函数内赋值的区别