diff --git a/README.md b/README.md index 82232df..af086b4 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ if __name__ == '__main__': # Runs main() if file wasn't imported. List ---- ```python + = [index] # First index is 0. Last -1. Allows assignments. = [] # Or: [from_inclusive : to_exclusive : ±step] ``` @@ -57,10 +58,11 @@ list_of_chars = list() * **Module [operator](#operator) provides functions itemgetter() and mul() that offer the same functionality as [lambda](#lambda) expressions above.** ```python -.insert(, ) # Inserts item at index and moves the rest to the right. - = .pop([]) # Removes and returns item at index or from the end. - = .count() # Returns number of occurrences. Also works on strings. + = len() # Returns number of items. Also works on other collections. + = .count() # Returns number of occurrences. Also `if in : ...`. = .index() # Returns index of the first occurrence or raises ValueError. + = .pop() # Removes and returns item from the end or at index if passed. +.insert(, ) # Inserts item at index and moves the rest to the right. .remove() # Removes first occurrence of the item or raises ValueError. .clear() # Removes all items. Also works on dictionary and set. ``` @@ -477,9 +479,9 @@ Format ### Ints ```python -{90:c} # 'Z' -{90:b} # '1011010' -{90:X} # '5A' +{90:c} # 'Z'. Unicode character with value 90. +{90:b} # '1011010'. Number 90 in binary. +{90:X} # '5A'. Number 90 in uppercase hexadecimal. ``` @@ -499,7 +501,7 @@ Numbers ### Basic Functions ```python - = pow(, ) # Or: ** + = pow(, ) # Or: ** = abs() # = abs() = round( [, ±ndigits]) # `round(126, -1) == 130` ``` @@ -605,8 +607,8 @@ from dateutil.tz import tzlocal, gettz ### Now ```python - = D/DT.today() # Current local date or naive DT. Also DT.now(). - = DT.now() # Aware DT from current time in passed timezone. + = D/DT.today() # Current local date or naive DT. Also DT.now(). + = DT.now() # Aware DT from current time in passed timezone. ``` * **To extract time use `'.time()'`, `'.time()'` or `'.timetz()'`.** @@ -1320,23 +1322,24 @@ class MyAbcSequence(abc.Sequence): +------------+------------+------------+------------+--------------+ ``` * **Method iter() is required for `'isinstance(, abc.Iterable)'` to return True, however any object with getitem() will work with any code expecting an iterable.** -* **Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping.** +* **Other extendable ABCs: MutableSequence, Set, MutableSet, Mapping, MutableMapping.** * **Names of their required methods are stored in `'.__abstractmethods__'`.** Enum ---- +**Class of named constants called members.** + ```python from enum import Enum, auto ``` ```python class (Enum): - = auto() - = - = , + = auto() # Increment of the last numeric value or 1. + = # Values don't have to be hashable. + = , # Tuple can be used for multiple values. ``` -* **Function auto() returns an increment of the last numeric value or 1.** * **Accessing a member named after a reserved keyword causes SyntaxError.** * **Methods receive the member they were called on as the 'self' argument.** @@ -1356,7 +1359,7 @@ class (Enum): ```python = type() # Returns member's enum. - = itertools.cycle() # Retruns endless iterator of members. + = itertools.cycle() # Returns endless iterator of members. = random.choice(list()) # Returns a random member. ``` @@ -1630,7 +1633,7 @@ from pathlib import Path ``` ```python - = os.getcwd() # Returns the current working directory. + = os.getcwd() # Returns current directory. Same as `$ pwd`. = os.path.join(, ...) # Joins two or more pathname components. = os.path.realpath() # Resolves symlinks and calls path.abspath(). ``` @@ -1654,7 +1657,7 @@ from pathlib import Path ```python = os.stat() # Or: .stat() - = .st_mtime/st_size/… # Modification time, size in bytes, ... + = .st_mtime/st_size/… # Modification time, size in bytes, ... ``` ### DirEntry @@ -1949,11 +1952,11 @@ with .begin(): ... # Exits the block with commit or Bytes ----- -**Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** +**A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** ```python = b'' # Only accepts ASCII characters and \x00-\xff. - = [] # Returns an int in range from 0 to 255. + = [index] # Returns an int in range from 0 to 255. = [] # Returns bytes even if it has only one element. = .join() # Joins elements using bytes as a separator. ``` @@ -1961,17 +1964,17 @@ Bytes ### Encode ```python = bytes() # Ints must be in range from 0 to 255. - = bytes(, 'utf-8') # Or: .encode('utf-8') - = .to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`. + = bytes(, 'utf-8') # Encodes string. Also .encode('utf-8'). = bytes.fromhex('') # Hex pairs can be separated by whitespaces. + = .to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`. ``` ### Decode ```python = list() # Returns ints in range from 0 to 255. - = str(, 'utf-8') # Or: .decode('utf-8') + = str(, 'utf-8') # Decodes bytes. Also .decode('utf-8'). + = .hex() # Returns hex pairs. Accepts `sep=`. = int.from_bytes(, …) # `byteorder='big/little', signed=False`. -'' = .hex() # Returns hex pairs. Accepts `sep=`. ``` ### Read Bytes from File @@ -2013,7 +2016,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * **`'<'` - Little-endian (i.e. least significant byte first).** * **`'>'` - Big-endian (also `'!'`).** -#### Besides numbers, pack() and unpack() also support bytes objects as part of the sequence: +#### Besides numbers, pack() and unpack() also support bytes objects as a part of the sequence: * **`'c'` - A bytes object with a single element. For pad byte use `'x'`.** * **`'s'` - A bytes object with n elements (not effected by byte order).** @@ -2035,10 +2038,10 @@ Array ```python from array import array - = array('', ) # Array from collection of numbers. + = array('', ) # Array from collection of numbers. = array('', ) # Array from bytes object. = array('', ) # Treats array as a sequence of numbers. -.fromfile(, n_items) # Appends items. Raises EOFError on end. +.fromfile(, n_items) # Appends items. Also frombytes(). = bytes() # Or: .tobytes() .write() # Writes array to the binary file. ``` @@ -2054,7 +2057,7 @@ Memory View ```python = memoryview() # Immutable if bytes, else mutable. - = [] # Returns an int or a float. + = [index] # Returns an int or a float. = [] # Mview with rearranged elements. = .cast('') # Casts memoryview to the new format. .release() # Releases memory buffer of target object. @@ -2068,10 +2071,10 @@ Memory View ``` ```python - = list() # Returns a list of ints or floats. - = str(, 'utf-8') # Treats mview as a bytes object. - = int.from_bytes(, …) # `byteorder='big/little', signed=False`. -'' = .hex() # Treats mview as a bytes object. + = list() # Returns a list of ints or floats. + = str(, 'utf-8') # Treats mview as a bytes object. + = .hex() # Returns hex pairs. Accepts `sep=`. + = int.from_bytes(, …) # `byteorder='big/little', signed=False`. ``` @@ -2779,7 +2782,7 @@ from PIL import Image ``` ```python - = .filter() # ` = ImageFilter.([])` + = .filter() # ` = ImageFilter.()` = .enhance() # ` = ImageEnhance.()` ``` @@ -3159,13 +3162,13 @@ Name: a, dtype: int64 ```python = .loc[key] # Or: .iloc[i] - = .loc[keys] # Or: .iloc[coll_of_i] - = .loc[from_key:to_key_inc] # Or: .iloc[from_i:to_i_exc] + = .loc[coll_of_keys] # Or: .iloc[coll_of_i] + = .loc[from_key : to_key_inc] # Or: .iloc[from_i : to_i_exc] ``` ```python = [key/i] # Or: . - = [keys/coll_of_i] # Or: [key/i : key/i] + = [coll_of_keys/coll_of_i] # Or: [key/i : key/i] = [bools] # Or: .loc/iloc[bools] ``` @@ -3216,7 +3219,7 @@ y 3 | | y 2 | y 2 | y 2 | +---------------+-------------+-------------+---------------+ ``` -* **Keys/indices/bools can't be tuples because `'obj[x, y]'` is converted to `'obj[(x, y)]'`!** +* **Indexing objects can't be tuples because `'obj[x, y]'` is converted to `'obj[(x, y)]'`!** * **Methods ffill(), interpolate(), fillna() and dropna() accept `'inplace=True'`.** * **Last result has a hierarchical index. Use `'[key_1, key_2]'` to get its values.** @@ -3354,8 +3357,8 @@ plt.show() # Displays the plot. Also plt.sav ``` ```python - = .to_dict(['d/l/s/…']) # Returns columns as dicts, lists or series. - = .to_json/html/csv([]) # Also to_markdown/latex([]). + = .to_dict('d/l/s/…') # Returns columns as dicts, lists or series. + = .to_json/html/csv/latex() # Saves output to file if path is passed. .to_pickle/excel() # Run `$ pip3 install "pandas[excel]" odfpy`. .to_sql('', ) # Also `if_exists='fail/replace/append'`. ``` diff --git a/index.html b/index.html index 4c144d4..c700dba 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -100,7 +100,8 @@ main() -

#List

<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
+

#List

<el>   = <list>[index]          # First index is 0. Last -1. Allows assignments.
+<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
 
<list>.append(<el>)             # Or: <list> += [<el>]
@@ -123,10 +124,11 @@ list_of_chars    = list(<str>)
 
  • For details about sorted(), min() and max() see sortable.
  • Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
  • -
    <list>.insert(<int>, <el>)      # Inserts item at index and moves the rest to the right.
    -<el>  = <list>.pop([<int>])     # Removes and returns item at index or from the end.
    -<int> = <list>.count(<el>)      # Returns number of occurrences. Also works on strings.
    +
    <int> = len(<list>)             # Returns number of items. Also works on other collections.
    +<int> = <list>.count(<el>)      # Returns number of occurrences. Also `if <el> in <coll>: ...`.
     <int> = <list>.index(<el>)      # Returns index of the first occurrence or raises ValueError.
    +<el>  = <list>.pop()            # Removes and returns item from the end or at index if passed.
    +<list>.insert(<int>, <el>)      # Inserts item at index and moves the rest to the right.
     <list>.remove(<el>)             # Removes first occurrence of the item or raises ValueError.
     <list>.clear()                  # Removes all items. Also works on dictionary and set.
     
    @@ -435,9 +437,9 @@ Point(x=1, y=2
  • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
  • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
  • -

    Ints

    {90:c}                                   # 'Z'
    -{90:b}                                   # '1011010'
    -{90:X}                                   # '5A'
    +

    Ints

    {90:c}                                   # 'Z'. Unicode character with value 90.
    +{90:b}                                   # '1011010'. Number 90 in binary.
    +{90:X}                                   # '5A'. Number 90 in uppercase hexadecimal.
     

    #Numbers

    <int>      = int(<float/str/bool>)                # Or: math.floor(<float>)
    @@ -453,7 +455,7 @@ Point(x=1, y=2
     
  • Floats can be compared with: 'math.isclose(<float>, <float>)'.
  • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.
  • -

    Basic Functions

    <num> = pow(<num>, <num>)                         # Or: <num> ** <num>
    +

    Basic Functions

    <num> = pow(<num>, <num>)                         # Or: <number> ** <number>
     <num> = abs(<num>)                                # <float> = abs(<complex>)
     <num> = round(<num> [, ±ndigits])                 # `round(126, -1) == 130`
     
    @@ -528,8 +530,8 @@ Point(x=1, y=2
  • Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).
  • Use '<D/DT>.weekday()' to get the day of the week as an int, with Monday being 0.
  • -

    Now

    <D/DTn>  = D/DT.today()                     # Current local date or naive DT. Also DT.now().
    -<DTa>    = DT.now(<tzinfo>)                 # Aware DT from current time in passed timezone.
    +

    Now

    <D/DTn> = D/DT.today()                      # Current local date or naive DT. Also DT.now().
    +<DTa>   = DT.now(<tzinfo>)                  # Aware DT from current time in passed timezone.
     
      @@ -1130,19 +1132,19 @@ Hello World!
      • Method iter() is required for 'isinstance(<obj>, abc.Iterable)' to return True, however any object with getitem() will work with any code expecting an iterable.
      • -
      • Abstract base classes that generate missing methods when extended are: Sequence, MutableSequence, Set, MutableSet, Mapping and MutableMapping.
      • +
      • Other extendable ABCs: MutableSequence, Set, MutableSet, Mapping, MutableMapping.
      • Names of their required methods are stored in '<abc>.__abstractmethods__'.
      -

      #Enum

      from enum import Enum, auto
      +

      #Enum

      Class of named constants called members.

      from enum import Enum, auto
       
      +
      class <enum_name>(Enum):
      -    <member_name> = auto()
      -    <member_name> = <value>
      -    <member_name> = <value>, <value>
      +    <member_name> = auto()              # Increment of the last numeric value or 1.
      +    <member_name> = <value>             # Values don't have to be hashable.
      +    <member_name> = <value>, <value>    # Tuple can be used for multiple values.
       
        -
      • Function auto() returns an increment of the last numeric value or 1.
      • Accessing a member named after a reserved keyword causes SyntaxError.
      • Methods receive the member they were called on as the 'self' argument.
      @@ -1157,7 +1159,7 @@ Hello World! <list> = [a.value for a in <enum>] # Returns enum's member values.
      <enum>   = type(<member>)               # Returns member's enum.
      -<iter>   = itertools.cycle(<enum>)      # Retruns endless iterator of members.
      +<iter>   = itertools.cycle(<enum>)      # Returns endless iterator of members.
       <member> = random.choice(list(<enum>))  # Returns a random member.
       

      Inline

      Cutlery = Enum('Cutlery', 'FORK KNIFE SPOON')
      @@ -1381,7 +1383,7 @@ p.add_argument('<name>', type=<type>
       from pathlib import Path
       
      -
      <str>  = os.getcwd()                # Returns the current working directory.
      +
      <str>  = os.getcwd()                # Returns current directory. Same as `$ pwd`.
       <str>  = os.path.join(<path>, ...)  # Joins two or more pathname components.
       <str>  = os.path.realpath(<path>)   # Resolves symlinks and calls path.abspath().
       
      @@ -1397,7 +1399,7 @@ p.add_argument('<name>', type=<type> <bool> = os.path.isdir(<path>) # Or: <DirEntry/Path>.is_dir()
      <stat> = os.stat(<path>)            # Or: <DirEntry/Path>.stat()
      -<real> = <stat>.st_mtime/st_size/…  # Modification time, size in bytes, ...
      +<num>  = <stat>.st_mtime/st_size/…  # Modification time, size in bytes, ...
       

      DirEntry

      Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.

      <iter> = os.scandir(path='.')       # Returns DirEntry objects located at the path.
       <str>  = <DirEntry>.path            # Returns the whole path as a string.
      @@ -1614,23 +1616,23 @@ CompletedProcess(args=['bc', #Bytes

      Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

      <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
      -<int>   = <bytes>[<index>]               # Returns an int in range from 0 to 255.
      +

      #Bytes

      A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.

      <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00-\xff.
      +<int>   = <bytes>[index]                 # Returns an int in range from 0 to 255.
       <bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
       <bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes as a separator.
       

      Encode

      <bytes> = bytes(<coll_of_ints>)          # Ints must be in range from 0 to 255.
      -<bytes> = bytes(<str>, 'utf-8')          # Or: <str>.encode('utf-8')
      -<bytes> = <int>.to_bytes(n_bytes, …)     # `byteorder='big/little', signed=False`.
      +<bytes> = bytes(<str>, 'utf-8')          # Encodes string. Also <str>.encode('utf-8').
       <bytes> = bytes.fromhex('<hex>')         # Hex pairs can be separated by whitespaces.
      +<bytes> = <int>.to_bytes(n_bytes, …)     # `byteorder='big/little', signed=False`.
       

      Decode

      <list>  = list(<bytes>)                  # Returns ints in range from 0 to 255.
      -<str>   = str(<bytes>, 'utf-8')          # Or: <bytes>.decode('utf-8')
      +<str>   = str(<bytes>, 'utf-8')          # Decodes bytes. Also <bytes>.decode('utf-8').
      +<str>   = <bytes>.hex()                  # Returns hex pairs. Accepts `sep=<str>`.
       <int>   = int.from_bytes(<bytes>, …)     # `byteorder='big/little', signed=False`.
      -'<hex>' = <bytes>.hex()                  # Returns hex pairs. Accepts `sep=<str>`.
       

      Read Bytes from File

      def read_bytes(filename):
      @@ -1661,7 +1663,7 @@ CompletedProcess(args=['bc', '=' - System's byte order (usually little-endian).
       
    • '<' - Little-endian (i.e. least significant byte first).
    • '>' - Big-endian (also '!').
    • -

    Besides numbers, pack() and unpack() also support bytes objects as part of the sequence:

      +

    Besides numbers, pack() and unpack() also support bytes objects as a part of the sequence:

    • 'c' - A bytes object with a single element. For pad byte use 'x'.
    • '<n>s' - A bytes object with n elements (not effected by byte order).

    Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:

      @@ -1683,10 +1685,10 @@ CompletedProcess(args=['bc', #Array

      List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method.

      from array import array
      -<array> = array('<typecode>', <collection>)    # Array from collection of numbers.
      +<array> = array('<typecode>', <coll_of_nums>)  # Array from collection of numbers.
       <array> = array('<typecode>', <bytes>)         # Array from bytes object.
       <array> = array('<typecode>', <array>)         # Treats array as a sequence of numbers.
      -<array>.fromfile(<file>, n_items)              # Appends items. Raises EOFError on end.
      +<array>.fromfile(<file>, n_items)              # Appends items. Also frombytes().
       <bytes> = bytes(<array>)                       # Or: <array>.tobytes()
       <file>.write(<array>)                          # Writes array to the binary file.
       
    @@ -1699,7 +1701,7 @@ CompletedProcess(args=['bc', <mview> = memoryview(<bytes/bytearray/array>) # Immutable if bytes, else mutable. -<real> = <mview>[<index>] # Returns an int or a float. +<real> = <mview>[index] # Returns an int or a float. <mview> = <mview>[<slice>] # Mview with rearranged elements. <mview> = <mview>.cast('<typecode>') # Casts memoryview to the new format. <mview>.release() # Releases memory buffer of target object. @@ -1711,10 +1713,10 @@ CompletedProcess(args=['bc', '<typecode>', <mview>) # Treats mview as a sequence of numbers. <file>.write(<mview>) # Writes mview to the binary file.
    -
    <list>  = list(<mview>)                        # Returns a list of ints or floats.
    -<str>   = str(<mview>, 'utf-8')                # Treats mview as a bytes object.
    -<int>   = int.from_bytes(<mview>, …)           # `byteorder='big/little', signed=False`.
    -'<hex>' = <mview>.hex()                        # Treats mview as a bytes object.
    +
    <list> = list(<mview>)                         # Returns a list of ints or floats.
    +<str>  = str(<mview>, 'utf-8')                 # Treats mview as a bytes object.
    +<str>  = <mview>.hex()                         # Returns hex pairs. Accepts `sep=<str>`.
    +<int>  = int.from_bytes(<mview>, …)            # `byteorder='big/little', signed=False`.
     

    #Deque

    A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

    from collections import deque
     <deque> = deque(<collection>)                  # Also `maxlen=None`.
    @@ -2276,7 +2278,7 @@ right = [[0.1,  0.6# Updates pixels with a copy of the sequence.
     <Image>.paste(<Image>, (x, y))                  # Draws passed image at specified location.
     
    -
    <Image> = <Image>.filter(<Filter>)              # `<Filter> = ImageFilter.<name>([<args>])`
    +
    <Image> = <Image>.filter(<Filter>)              # `<Filter> = ImageFilter.<name>(<args>)`
     <Image> = <Enhance>.enhance(<float>)            # `<Enhance> = ImageEnhance.<name>(<Image>)`
     
    <array> = np.array(<Image>)                     # Creates a 2d/3d NumPy array from the image.
    @@ -2590,11 +2592,11 @@ Name: a, dtype: int64
     <Sr> = pd.Series(<dict/Series>, index=<list>)  # Only keeps items with keys specified in index.
     
    <el> = <Sr>.loc[key]                           # Or: <Sr>.iloc[i]
    -<Sr> = <Sr>.loc[keys]                          # Or: <Sr>.iloc[coll_of_i]
    -<Sr> = <Sr>.loc[from_key:to_key_inc]           # Or: <Sr>.iloc[from_i:to_i_exc]
    +<Sr> = <Sr>.loc[coll_of_keys]                  # Or: <Sr>.iloc[coll_of_i]
    +<Sr> = <Sr>.loc[from_key : to_key_inc]         # Or: <Sr>.iloc[from_i : to_i_exc]
     
    <el> = <Sr>[key/i]                             # Or: <Sr>.<key>
    -<Sr> = <Sr>[keys/coll_of_i]                    # Or: <Sr>[key/i : key/i]
    +<Sr> = <Sr>[coll_of_keys/coll_of_i]            # Or: <Sr>[key/i : key/i]
     <Sr> = <Sr>[bools]                             # Or: <Sr>.loc/iloc[bools]
     
    <Sr> = <Sr> > <el/Sr>                          # Returns a Series of bools.
    @@ -2633,7 +2635,7 @@ y    3
     
      -
    • Keys/indices/bools can't be tuples because 'obj[x, y]' is converted to 'obj[(x, y)]'!
    • +
    • Indexing objects can't be tuples because 'obj[x, y]' is converted to 'obj[(x, y)]'!
    • Methods ffill(), interpolate(), fillna() and dropna() accept 'inplace=True'.
    • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
    @@ -2746,8 +2748,8 @@ plt.show() # Disp <DF> = pd.read_pickle/excel('<path/url>') # Use `sheet_name=None` to get all Excel sheets. <DF> = pd.read_sql('<table/query>', <conn.>) # SQLite3/SQLAlchemy connection (see #SQLite).
    -
    <dict> = <DF>.to_dict(['d/l/s/…'])             # Returns columns as dicts, lists or series.
    -<str>  = <DF>.to_json/html/csv([<path>])       # Also to_markdown/latex([<path>]).
    +
    <dict> = <DF>.to_dict('d/l/s/…')               # Returns columns as dicts, lists or series.
    +<str>  = <DF>.to_json/html/csv/latex()         # Saves output to file if path is passed.
     <DF>.to_pickle/excel(<path>)                   # Run `$ pip3 install "pandas[excel]" odfpy`.
     <DF>.to_sql('<table_name>', <connection>)      # Also `if_exists='fail/replace/append'`.
     
    @@ -2934,7 +2936,7 @@ $ deactivate # Deactivates the activ