EffectivePython: str and bytes, generator expression, enumerate

1. Thinking in a pythonic way

"""View version"""
import sys
sys.version_info(major=3, minor=6, micro=3, releaselevel='final', serial=0)
3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)]
"""Modify path"""
import os
os.chdir(r'C:\Users\Xiaowang Zhang\Desktop\code')
"""Check code style"""
from pylint import epylint as lint
(pylint_stdout, pylint_stderr) = lint.py_run('rule3_ml.py',return_std=True)

3.bytes str and unicode

  • Python 3 has two types of character sequences: bytes and str. An instance of bytes contains the original bytes; an instance of STR contains unicode characters.
  • There are also two representations of python2, STR and unicode. The str instance contains the original bytes, and unicode contains unicode characters.
    • Encode: converts unicode to binary data.
    • Decode: convert binary to unicode data.
      Tip: the core part of a python program should use unicode character types.
"""python3 Medium acceptance bytes and str Return str Function of"""
def to_str(bytes_or_str):
    if isinstance(bytes_or_str, bytes):
        value = bytes_or_str.decode('utf-8')
        value = bytes_or_str
    return value
"""python3 Medium acceptance bytes and str Return bytes Function of"""
def to_bytes(bytes_or_str):
    if isinstance(bytes_or_str, str):
        value = bytes_or_str.encode('utf-8'):
        value = bytes_or_str
    return value

9. List derivation with large amount of rewriting data by generator expression

  • Put the writing method used to implement list derivation in a pair of parentheses, which is the generator expression.
value = [len(x) for x in open('/tmp/my_file.txt')]
"""If the file is too large, use the builder expression"""
it = (len(x) for x in open('/tmp/my_file.txt'))
"""The result of printing is generator"""
"""Use built-in next Function takes the next value from the generator"""
"""Output: 100 57"""

10. Try to replace range with enumerate

from random import *
random_bits = 0
for i in range(64):
    if randint(0, 1):
        random_bits |= 1 << i
flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
for flavor in flavor_list:
    print('%s is delicious '% flavor)
vanilla is delicious 
chocolate is delicious 
pecan is delicious 
strawberry is delicious 
"""iteration list When index is needed"""
for i in range(len(flavor_list)):
    flavor = flavor_list[i]
    print('%d: %s' % (i + 1, flavor))
1: vanilla
2: chocolate
3: pecan
4: strawberry
"""The better way is to use enumerate"""
for i, flavor in enumerate(flavor_list):
    print('%d: %s' % (i + 1, flavor))
1: vanilla
2: chocolate
3: pecan
4: strawberry
  • enumerate can wrap various iterators into generators.
  • The generator produces a heap of output values one at a time, the former representing loop subscripts, and the latter representing elements from the next sequence in the iterator.
"""You can also specify enumerate The value used when the function starts counting"""
for i, flavor in enumerate(flavor_list, 1):
    print('%d: %s' % (i, flavor))
1: vanilla
2: chocolate
3: pecan
4: strawberry

Tags: Python Anaconda

Posted on Mon, 04 May 2020 08:09:56 -0700 by bubblenut