Detailed python collections module

  collections involving the following modules:

  [‘deque’, ‘defaultdict’, ‘namedtuple’, ‘UserDict’, ‘UserList’,

  ‘UserString’, ‘Counter’, ‘OrderedDict’, ‘ChainMap’]

  Detailed namedtuple

  tuple

  tuple unpacking properties

  $ ipython

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: user_tuple = ( 'laoliu', 30, 175, 'beijing')

  Unpacking the characteristics of # python

  In [2]: name, *other = user_tuple

  In [3]: name

  Out [3]: 'Candy'

  In [4]: other

  Out[4]: [30, 175, 'beijing']

  # Unpacking

  In [5]: name, age, hight, address = user_tuple

  In [6]: print(name, age, hight, address)

  laoliu 30 175 beijing

  In [7]: d = {}

  # Dict tuple as a key, but not list, because the tuple is immutable

  In [8]: d[user_tuple] = 'shanghai'

  In [9]: d

  Out [9]: {( 'laoliu', 30, 175, 'beijing'): 'shanghai'}

  The exemplary use namedtuple

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: from collections import namedtuple

  In [2]: User = namedtuple("User",['name', 'age'])

  In [3]: user = User(name='liu',age=18)

  In [4]: print(user.name, user.age)

  liu 18

  In [5]: user_tuple = ('zhang', 19)

  # * To pass parameters, but also the position parameter, parameter passing mode Detailed reference is a function of

  In [6]: user2 = User(*user_tuple)

  In [7]: print(user.name, user.age)

  liu 18

  In [8]: print(user2.name, user2.age)

  zhang 19

  In [9]: user_dict = {'name': 'wang', 'age':20}

  ** # to mass participation, that is, the keyword parameters, parameter passing mode may explain the reference function

  In [10]: user3 = User(**user_dict)

  In [11]: print(user3.name, user3.age)

  wang 20

  After the settlement of new property #

  In [12]: User = namedtuple('User',['name', 'age', 'height'])

  In [13]: user = User(name='liu',age=18)

  ---------------------------------------------------------------------------

  TypeError Traceback (most recent call last)

  in

  ----> 1 user = User(name='liu',age=18)

  TypeError: __new__() missing 1 required positional argument: 'height'

  # The first solution is to add keywords

  In [14]: user = User(name='liu',age=18, height=170)

  In [15]: print(user.name, user.age, user.height)

  liu 18 170

  In [16]: print(user2.name, user2.age, user2.height)

  ---------------------------------------------------------------------------

  AttributeError Traceback (most recent call last)

  in

  ----> 1 print(user2.name, user2.age, user2.height)

  AttributeError: 'User' object has no attribute 'height'

  In [17]: user2

  Out[17]: User(name='zhang', age=19)

  Examples of positional parameters and keyword arguments mix of # This is the function parameter passing in

  In [18]: user2 = User(*user_tuple, height=171)

  In [19]: user2

  Out[19]: User(name='zhang', age=19, height=171)

  In [20]: user3

  Out[20]: User(name='wang', age=20)

  # Error with the reference example

  In [21]: use3 = User(**user_dict, 'height':172)

  File "", line 1

  use3 = User(**user_dict, 'height':172)

  ^

  SyntaxError: invalid syntax

  # Error with the reference example

  In [22]: use3 = User(**user_dict, {'height': 172})

  File "", line 1

  use3 = User(**user_dict, {'height': 172})

  ^

  SyntaxError: positional argument follows keyword argument unpacking

  In [23]: user_dict

  Out[23]: {'name': 'wang', 'age': 20}

  In [24]: user_dict.update({'height':172})

  In [25]: user_dict

  Out[25]: {'name': 'wang', 'age': 20, 'height': 172}

  In [26]: user3 = User(**user_dict)

  In [27]: user3

  Out[27]: User(name='wang', age=20, height=172)

  defaultdict uses detailed

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: from collections import defaultdict

  In [2]: users = ['liu1', 'liu2', 'liu3', 'liu1', 'liu1', 'liu2']

  # Of times each name appears in the statistics users: In [3]

  In [4]: user_dict = {}

  # This is our common approach to solving

  In [5]: for user in users:

  ...: if user in user_dict:

  ...: user_dict[user] += 1

  ...: else:

  ...: user_dict[user] = 1

  ...:

  In [6]: user_dict # Results

  Out[6]: {'liu1': 3, 'liu2': 2, 'liu3': 1}

  # Second solution, using setdefault ()

  In [7]: user_dict2 = {}

  In [8]: for user in users:

  ...: user_dict2.setdefault(user, 0)

  ...: user_dict2[user] += 1

  ...:

  In [9]: user_dict2

  Out[9]: {'liu1': 3, 'liu2': 2, 'liu3': 1}

  # Third solution using defaultdict () (recommended)

  In [10]: user_dict3 = defaultdict(int)

  In [11]: for user in users:

  ...: user_dict3[user] += 1

  ...:

  In [12]: user_dict3

  Out[12]: defaultdict(int, {'liu1': 3, 'liu2': 2, 'liu3': 1})

  # Defaultdict () extended use, create some complex data structures

  # Request the following data structure:

  {

  'group1':{

  'name': '',

  'nums': 0

  }

  }

  In [13]: def gen_default():

  ...: return {'name': '', 'nums': 0}

  ...:

  In [14]: default_dict = defaultdict(gen_default)

  In [15]: default_dict['group1']

  Out[15]: {'name': '', 'nums': 0}

  Detailed use deque

  deque is thread-safe, list non-thread-safe, in the case of multi-threaded programming to pay more attention

  queue (queue) is actually implemented in the deque

  deque is written in C, very fast, you can always use

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: from collections import deque

  In [2]: a = ['b', 'c', 'd']

  # The list into deque

  In [3]: = a_duque and (a)

  In [4]: a_duque

  Out [4]: ​​deque ([ 'b', 'c', 'd'])

  # Tuple into the deque

  In [5]: b = (1,2, 3)

  At [6]: = b_duque and (b)

  In [7]: b_duque

  Out [7] and ([1, 2, 3])

  In [8]: c = {"a": 1, "b": 2, "c": 4}

  # The dice into deque

  [9]: = c_deque and (c)

  In [10], c_deque

  Out[10]: deque(['a', 'b', 'c'])

  # Deque in append operation, the same list

  In [11], c_deque.append ( 'D')

  In [12], c_deque

  Out [12]: deque ([ 'a', 'b', 'c', 'd'])

  # Deque.appendleft () to add elements to the left of position 0

  In [13], c_deque.appendleft ( 'e')

  In [14]: c_deque

  Out [14] deque ([ 'e', ​​'a', 'b', 'c', 'd'])

  # Shallow copy

  In [15]: = c_deque_copy c_deque.copy ()

  In [16]: c_deque_copy.count()

  ---------------------------------------------------------------------------

  TypeError Traceback (most recent call last)

  in

  ----> 1 c_deque_copy.count()

  TypeError: count() takes exactly one argument (0 given)

  # Find the number of occurrences of an element

  In [17]: c_deque_copy.count('a')

  Out[17]: 1

  In [18]: c_deque_copy

  Out [18]: deque ([ 'e', ​​'a', 'b', 'c', 'd'])

  In [19]: c_deque_copy [1] = 'A1'

  In [20], c_deque_copy

  Out [20]: deque ([ 'e', ​​'a1', 'b', 'c', 'd'])

  In [21]: c_deque

  Out [21] deque ([ 'e', ​​'a', 'b', 'c', 'd'])

  # Merge two deque, the deque which merge to the right of the former, modification site, return None

  In [22]: c_deque.extend (a_duque)

  In [23]: c_deque

  Out[23]: deque(['e', 'a', 'b', 'c', 'd', 'b', 'c', 'd'])

  # Merge two deque, who will deque full merger of the former to the left, place editing, return None

  In [24]: c_deque.extendleft(b_duque)

  In [25]: c_deque

  Out[25]: deque([3, 2, 1, 'e', 'a', 'b', 'c', 'd', 'b', 'c', 'd'])

  # Returns the index position of the element

  In [26]: c_deque.index ( 'B')

  Out[26]: 5

  Given position in the insert elements #

  In [27]: c_deque.insert(2,'f')

  In [28]: c_deque

  Out[28]: deque([3, 2, 'f', 1, 'e', 'a', 'b', 'c', 'd', 'b', 'c', 'd'])

  In [29]: c_deque.rotate ( 'a')

  ---------------------------------------------------------------------------

  TypeError Traceback (most recent call last)

  in

  ----> 1 c_deque.rotate ( 'a')

  TypeError: 'str' object cannot be interpreted as an integer

  # Before the specified number of elements of the tail into the team, the default is 1

  In [30]: c_deque.rotate ()

  In [31]: c_deque

  Out[31]: deque(['d', 3, 2, 'f', 1, 'e', 'a', 'b', 'c', 'd', 'b', 'c'])

  # Reverse the entire deque

  In [32]: c_deque.reverse ()

  In [33]: c_deque

  Out[33]: deque(['c', 'b', 'd', 'c', 'b', 'a', 'e', 1, 'f', 2, 3, 'd'])

  In [34]:

  Counter uses detailed

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: from collections import Counter

  In [2]: users = ['liu1', 'liu2', 'liu3', 'liu1', 'liu1', 'liu2']

  # Of statistical data list

  In [3]: users_counter = Counter(users)

  In [4]: users_counter

  Out[4]: Counter({'liu1': 3, 'liu2': 2, 'liu3': 1})

  # Character statistics, the number of times each character appears

  In [5]: test = Counter('abcddfdefadsfasdjfoaisdfjasdjfasdfasdfasdfgfhdf')

  In [6]: test

  Out[6]:

  Counter({'a': 8,

  'b': 1,

  'c': 1,

  'd': 11,

  'f': 11,

  'e': 1,

  's': 7,

  'j': 3,

  'O' 1,

  'i': 1,

  'g': 1,

  'h': 1})

  # Statistics two characters in the string occurrences, Method 1

  In [7]: test.update('aadfd')

  In [8]: test

  Out[8]:

  Counter({'a': 10,

  'b': 1,

  'c': 1,

  'd': 13,

  'f': 12,

  'e': 1,

  's': 7,

  'j': 3,

  'O' 1,

  'i': 1,

  'g': 1,

  'h': 1}) Wuxi abortion how much money http://www.bhnnk120.com/

  # Statistics two characters in the string occurrences, Method 2

  In [9]: test2 = Counter('abcde')

  In [10]: test.update(test2)

  In [11]: test

  Out[11]:

  Counter({'a': 11,

  'b': 2,

  'c': 2,

  'd': 14,

  'f': 12,

  'e': 2,

  's': 7,

  'j': 3,

  'O' 1,

  'i': 1,

  'g': 1,

  'h': 1})

  # TOP n statistical methods

  In [12]: test.most_common(3)

  Out[12]: [('d', 14), ('f', 12), ('a', 11)]

  OrderedDict uses detailed

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: from collections import OrderedDict

  In [2]: user_dict = OrderedDict()

  In [3]: user_dict['b'] = 'liu'

  In [4]: user_dict['a'] = 'liu1'

  In [5]: user_dict['c'] = 'liu2'

  In [6]: user_dict

  Out[6]: OrderedDict([('b', 'liu'), ('a', 'liu1'), ('c', 'liu2')])

  # Eject the last item.

  In [7]: user_dict.popitem()

  Out[7]: ('c', 'liu2')

  In [8]: user_dict

  Out[8]: OrderedDict([('b', 'liu'), ('a', 'liu1')])

  # Mobile element to the last used scene priority

  In [9]: user_dict.move_to_end('b')

  In [10]: user_dict

  Out[10]: OrderedDict([('a', 'liu1'), ('b', 'liu')])

  Finally a pop # key, key returns the corresponding value

  In [11]: user_dict.pop('b')

  Out[11]: 'liu'

  In [12]: user_dict

  Out[12]: OrderedDict([('a', 'liu1')])

  ChainMap uses detailed

  Python 3.7.3 (default, Mar 28 2019, 10:38:38) [MSC v.1915 32 bit (Intel)]

  Type 'copyright', 'credits' or 'license' for more information

  IPython 7.4.0 -- An enhanced Interactive Python. Type '?' for help.

  In [1]: from collections import ChainMap

  In [2]: dict1 = {'a': 'liu', 'b': "liu1"}

  In [3]: dict2 = {"c": "liu3", 'd': 'liu4'}

  # Most commonly used method is to connect a plurality of dict, if the key is repeated, taking only the first key in a dict

  In [4]: new_dict = ChainMap(dict1, dict2)

  In [5]: for key, value in new_dict.items():

  ...: print(key, value)

  ...:

  c liu3

  d liu4

  a liu

  b liu1

  # Modify dict2, so that one of the keys and key repeat dict1

  In [6]: dict2 = {"b": "liu3", 'd': 'liu4'}

  In [7]: new_dict = ChainMap(dict1, dict2)

  In [8]: for key, value in new_dict.items():

  ...: print(key, value)

  ...:

  b liu1

  d liu4

  a liu

  In [9]: new_dict

  Out[9]: ChainMap({'a': 'liu', 'b': 'liu1'}, {'b': 'liu3', 'd': 'liu4'})

  # Return dict the list, but only point to the original dict, not the original copy of dict

  In [10]: new_dict.maps

  Out[10]: [{'a': 'liu', 'b': 'liu1'}, {'b': 'liu3', 'd': 'liu4'}]

  In [11]: new_dict.maps[0]['a'] = 'liu333'

  In [12]: new_dict

  Out[12]: ChainMap({'a': 'liu333', 'b': 'liu1'}, {'b': 'liu3', 'd': 'liu4'})

  In [13]: dict1

  Out[13]: {'a': 'liu333', 'b': 'liu1'}


Guess you like

Origin blog.51cto.com/14335413/2431291