Python Other data Structures Collection module-namtuple defaultdict deque Queue Counter orderdict

Source: Internet
Author: User
Tags delete key

Nametuple

is a tuple extension subclass, named tuples, essentially simple class objects

From collections Import Namedtupleinfo = Namedtuple ("Info", [' Name ', ' age ', ' height ']) # Assignment, is not a bit like object-oriented instance variable mode Info.name = " North Gate Blowing Snow "info.age = 18info.height = 175# Access print (info.name)

is essentially the same as in the following way

Class Info:    def __init__ (self):        self.name = none        self.age = none        self.height = none        Passinfo = Info ( # Assignment Info.name = "North gate blowing Snow" info.age = 18info.height = 175# Access print (info.name)

 Related methods

1. _make initialization assignment, must be of the same length

From collections Import Namedtupleinfo = Namedtuple ("Info", [' Name ', ' age ', ' height ']). _make (["North Gate blowing Snow", 18, 175]) # Access Print ( Info.name)

2. _asdict Converts the Nametuple object to a Dictionary object, which is an ordered dictionary

From collections Import Namedtupleinfo = Namedtuple ("Info", [' Name ', ' age ', ' height ']). _make (["North Gate blowing Snow", 18, 175]) # Access Print ( Info._asdict ())

  

  

Defaultdict

is a dict extension class that accesses the dictionary key if it is not, automatically sets the default value and adds the dictionary

info = dict () name = Info.setdefault (' name ', "North Gate Blown Snow") print (name, info) from collections import defaultdict# default value must be an iterative object info = Defaultdict (lambda: "North gate blowing Snow") name = info[' name ']print (name, info)

  

Deque  

Double-ended queue, operation and list similar

  list deque is recommended for saving the same similar data , related methods and list consistent

Features: deque is thread safe , list is not thread safe, multithreaded programming uses deque

From collections Import Dequenames = Deque () names.append ("North Gate Blowing Snow") names.append ("Qiniuyun") Names.insert (0, "today's headline") Print (names)

  

Queue   

Queue (FIFO), implemented via Deque

Core two methods put get, will clog

From queue import Queuemessage = queue () # Put data message.put ("North Gate Blowing Snow") # Consumer data print (Message.get ())

  

Counter 

The number of statistical occurrences of an iterative object, the direct return of statistical results, is the subclass of Dict

From collections import Counterfrom random import randintnumbers = [Randint (1, 5) for _ in range]numbers_count = Count ER (numbers) print (Numbers_count)

Related methods

1. update to add new data

From collections import Counterfrom random import randintnumbers = [Randint (1, 5) for _ in range]numbers_count = Count ER (numbers) print (numbers_count) # Add new Data Numbers_count.update ([Randint (1, ten) for _ in range]) print (numbers_count)

2. Most_common (n) the top n elements of the current number of output occurrences

From collections import Counterfrom random import randintnumbers = [Randint (1, 5) for _ in range]numbers_count = Count ER (numbers) print (numbers_count) # Add new Data Numbers_count.update ([Randint (1, ten) for _ in range]) print (numbers_count) # The first 3 elements of the current maximum number of output occurrences, return to the list print (Numbers_count.most_common (3))

  

Orderdict

Inherit dict, keep dictionary add order, have dict all methods

From collections Import Ordereddictinfo = Ordereddict () # Fill in Data info["name"] = "North gate blowing Snow" info[' age '] = 18info[' height '] = 175prin T (info)

Other methods

1. Popitem Deletes the last key:value by default and returns

From collections Import Ordereddictinfo = Ordereddict () # Fill in Data info["name"] = "North gate blowing Snow" info[' age '] = 18info[' height '] = 175# return Tuple form print (Info.popitem (' name '))

2. Pop must pass in key, delete Key:value, return value

From collections Import Ordereddictinfo = Ordereddict () # Fill in Data info["name"] = "North gate blowing Snow" info[' age '] = 18info[' height '] = 175# return The value of age corresponds to print (Info.pop (' age '))

3. move_to_end incoming key, move element to last

From collections Import Ordereddictinfo = Ordereddict () # Fill in Data info["name"] = "North gate blowing Snow" info[' age '] = 18info[' height ' = 175# move Data info.move_to_end (' age ') print (info)

  

Experience:

1. These data types are based on the extension of the list tuple set dict basic data type, which essentially adds some features

Python Other data Structures Collection module-namtuple defaultdict deque Queue Counter orderdict

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.