Third week of Python study notes (1)

Source: Internet
Author: User
Tags iterable local time string format timedelta

Dictionary
    • A collection of data for Key-value key-value pairs
    • Variable, unordered, key non-repeating
Initialization
d = dict()d = {}d = dict(**kwargs)  如:d = dict(a=1,b=2)dict(iterable, **kwarg)

Constructs a dictionary using an iterative object and a Name=value pair, but the elements of an iterative object must be a two-tuple structure

dict(mapping, **kwarg)dict.fromkeys(iterable, value)
Access to dictionary elements
    • D[key]
      • Returns the value corresponding to key
      • Key does not exist throwing Keyerror exception
    • Get (key[, default])
      • Returns the value corresponding to key
      • Key does not exist return default value, return None if default value is not set
    • SetDefault (key[, default])
      • Returns the value corresponding to key
      • Key does not exist, adds a kv pair, value is default, and returns default if default is not set, default is None
Dictionary Additions and modifications
    • D[key] = value
      • Change the value corresponding to key to value
      • Key does not exist adding a new kv pair
    • Update ([other]), None
      • Update this dictionary with the kv pair of another dictionary
      • Key does not exist, just add
      • Key exists, overwriting the value corresponding to the existing key
      • In-place modification
d.update(red=1)d.update(((‘red‘,2),))d.update({‘red‘:3})
Dictionary Delete
    • Pop (key[, default])
      • Key exists, removes it, and returns its value
      • Key does not exist, returns the given default
      • Default is not set, key does not exist throw Keyerror exception
    • Popitem ()

      • Removes and returns an arbitrary key-value pair
      • The dictionary is empty and throws a Keyerror exception
      • Clear ()
      • Empty dictionary
    • Del statement
      • Essentially reduces the reference to an object, Del actually removes the name, not the object
Dictionary traversal:
    • Traverse Key:
for k in d:print(k)for k in d.keys():print(k)
    • Traverse values:
for k in d:print(d[k])for k in d:print(d.get(k))for v in d.values():print(v)

* traverse Item, that is, KV pair:

for item in d.items():print(item)for item in d.items():print(item[0], item[1])for k,v in d.items():print(k, v)for k, _ in d.items():print(k)for _ ,v in d.items():print(v)
Summarize
    • In Python3, the keys, values, items method returns an iterative object that resembles a generator, and does not copy the return result of the function into memory
      • Dictionary View Object
      • The entry dynamic view of the dictionary, the dictionary changes, the view will reflect these changes
Dictionary traversal and Removal
    • Adding or deleting elements is not allowed when traversing a dictionary
    • You can log the key value before traversing delete
d = dict(a=1, b=2, c=‘abc‘)keys = []for k,v in d.items():if isinstance(v, str):keys.append(k)for k in keys:d.pop(k)print(d)
Defaultdict
    • Collections.defaultdict ([default_factory[, ...])
    • The first parameter is Default_factory, the default is None, and it provides an initialization function. When the key does not exist, the factory function is called to generate the value corresponding to the key.
Ordereddict
    • Collections. Ordereddict ([items])
    • Keys are not listed in the order in which they are added, you can use the Ordereddict record order
Standard library DateTime DateTime module
    • DateTime class
    • Today ()
      • Returns a DateTime object for the current time of the local time zone
    • Now (Tz=none)
      • Returns the DateTime object of the current time, in microseconds, if TZ is none, and returns to today ()
      • Fromtimestamp (timestamp, tz=none) returns a DateTime object from a timestamp
    • Date formatting
      • Class method Strptime (date_string, format), returning a DateTime object
      • Object method strftime (format), return string
      • Formatting the string Format function
import datetimedt = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")print(dt.strftime("%Y-%m-%d %H:%M:%S"))print("{0:%Y}/{0:%m}/{0:%d} {0:%H}::{0:%M}::{0:%S}".format(dt))
    • Timedelta Object

      • Add and subtract from a DateTime object
      • Datetime.timedelta (days=0, seconds=0, Microseconds=0, Milliseconds=0,minutes=0, hours=0, weeks=0)
      • Total_seconds () returns the total number of seconds of the time difference
    • Standard library Time
      • Time.sleep (secs) suspends the calling thread for the specified number of seconds
List analytic type
    • Grammar

      • [return value for element in iteration object if condition]
      • Use brackets [], Inside is for loop, if conditional statement optional
      • Returns a new list
    • List parsing is a syntactic sugar
      • The compiler optimizes, does not affect efficiency because of shorthand, but improves efficiency because of optimization
      • Reduce programmer workload and reduce errors
      • Simplified code, but improved readability
List Resolution Advanced
    • [Expr for item in iterable if Cond1 if COND2]
    • Equivalent to

      ret = []for item in iterable:if cond1:if cond2:ret.append(expr)
    • [Expr for I in Iterable1 for J in Iterable2]
      Equivalent to
      ret = []for i in iterable1:for j in iterable2:ret.append(expr)
Builder expression
    • (return value for element in can iterate object if condition)

      • The generator expression is calculated on demand (or lazy evaluation, lazy calculation), and the value is calculated when needed
      • List parsing is an immediate return value
    • The generator is an iterative object, an iterator

    • Using Next (itetator) iteration
Generator iterations vs. list iterations
    • Generator

      • Deferred calculation
      • Returns an iterator that can iterate
      • You can't look back after you've walked through the past.
    • List

      • Calculate Now
      • Returns an iterator that returns a list of objects that can be iterated
      • You can go back to the iteration after you've walked through the front and back again.
    • Calculation method
      • Generator expression Deferred calculation, list parsing immediate calculation
    • Memory consumption
      • Single from the return value itself, the generator expression saves memory, and the list resolves to return the new list
      • The generator does not have data, memory consumption is very small, but when used, although the return of data, but combined to occupy the same amount of memory
      • List parsing constructs a new list needs to occupy memory
    • Calculation speed
      • The generator expression takes a very short time to look at the calculation, and the list parsing is time-consuming
      • But the generator itself does not return any values, only one generator object is returned
      • List parsing constructs and returns a new list
Set Analytic type
    • {The return value for element in can iterate object if condition}
      • Returns a collection immediately
Dictionary analytic type
    • {The return value for element in can iterate object if condition}
      • Use Key:value form
      • Returns a dictionary immediately
Built-in functions
  • Identity ID
    • Returns the unique identity of the object, CPython returns the memory address
  • Hashed Hash ()
    • Returns the hash value of an object
  • Types Type ()
    • Returns the type of the object
  • Type conversions
    float () int () bin () Hex () Oct () bool () list () tuple () Dict () set () complex () bytes () ByteArray ()
  • Enter input ([prompt])

    • Receives user input, returns a string
    • Printing print (*objects, sep= ", end= ' \ n ', File=sys.stdout, Flush=false)
    • printout, default with space split, wrap end, output to console
  • Object length Len (s)
    • Returns the number of elements of a collection type
  • Isinstance (obj, class_or_tuple)

    • Determines whether the object obj belongs to a type or a type listed in a tuple
    • Isinstance (True, int)
  • Issubclass (CLS, class_or_tuple)

    • Determines whether the type CLS is a subclass of a type or a subcategory of a type listed in a tuple
    • Issubclass (bool, int)
  • Absolute ABS (x)
    • X is numeric
  • Max Max () min min ()
    • Returns the maximum or minimum value in an object that can be iterated
    • Returns the maximum or minimum value in multiple parameters
  • Round (x)
    • Four homes six into the five take, round (-0.5)
  • Pow (x, y)
    • Equivalent to X**y
  • Range (stop)
    • An iterative object from 0 to Stop-1, range (start, stop[, step]) from start to stop-1 to end step as step
  • Divmod (x, y)
    • Equivalent to tuple (x//y, x%y)
  • Sum (iterable[, start])

    • Sums all numeric elements of an object that can be iterated
    • SUM (range (1,100,2))
  • Chr (i)
    • Returns the corresponding character to a range of integers
  • Ord (c)

    • Returns the integer corresponding to the character
  • Sorted (iterable[, key][, reverse]) sort
    • Returns a new list, ascending by default
  • Reversed ()

    • Reverse
  • Enumeration enumerate (SEQ, start=0)

    • Iterates over a sequence that returns a two-tuple of indexed numbers and elements
      *start A number that represents the start of the index, which is 0 by default
  • Iterators and fetching elements ITER (iterable), Next (iterator[, default])

    • Iter encapsulates an iterative object into an iterator
    • Next removes an element from an iterator. If all the elements have been taken, then next will throw a Stopiteration exception
  • Zip function zip (*iterables)
    • Like a zipper, a number of iterative objects are merged together to return an iterator
    • Merges each element from a different object into a single tuple
    • Bucket principle, take the minimum number of iterations iteration
Can iterate over objects
    • The ability to iterate over and over again to return objects of different elements.
    • The so-called same, does not mean whether the value is the same, but whether the element is the same in the container, such as the list of values can be repeated, [' A ', ' a '], although the list has 2 elements, the same value, but two ' a ' is a different element
    • Can iterate, but not necessarily orderly, may not be indexed
    • The object can be iterated: list, tuple, string, Bytes, ByteArray, range, set, dict, generator, etc.
    • You can use the member operator in, not In,in is essentially traversing the object
Iterators
    • A special object, which must be an iterative object with the characteristics of an iterative object
    • To encapsulate an iterative object into an iterator using the ITER method
    • Iterate through the iterator object with the next method
    • The Builder object, which is the iterator object

Third week of Python study notes (1)

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.