EffectivePython:str和bytes,生成器表达式,enumerate

来源:互联网 发布:鹏业算量软件好吗 编辑:程序博客网 时间:2024/05/22 12:12

1.用pythonic方式思考

"""查看版本"""import sysprint(sys.version_info)print(sys.version)
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)]
"""修改路径"""import osos.getcwd()os.chdir(r'C:\Users\Xiaowang Zhang\Desktop\code')
"""检测代码风格"""from pylint import epylint as lint(pylint_stdout, pylint_stderr) = lint.py_run('rule3_ml.py',return_std=True)

3.bytes str and unicode

  • python3有两种表示字符序列的类型:bytes和str。bytes的实例包含的是原始的字节;str的实例包含的是unicode字符。
  • python2也有两种表示,str和unicode。str实例包含的是原始的字节,unicode包含的是unicode字符。
    • Encode(编码):把unicode转成二进制数据。
    • Decode(解码):把二进制转成unicode数据。
      tip:Python程序的核心部分应该使用unicode字符类型。
"""python3中接受bytes和str返回str的函数"""def to_str(bytes_or_str):    if isinstance(bytes_or_str, bytes):        value = bytes_or_str.decode('utf-8')    else:        value = bytes_or_str    return value"""python3中接受bytes和str返回bytes的函数"""def to_bytes(bytes_or_str):    if isinstance(bytes_or_str, str):        value = bytes_or_str.encode('utf-8'):    else:        value = bytes_or_str    return value

9.生成器表达式改写数据量较大的列表推导

  • 把实现列表推导所用的写法放在一对圆括号里,就是生成器表达式了。
"""例子"""value = [len(x) for x in open('/tmp/my_file.txt')]print(value)"""输出:[100,57,........]""""""如果文件过大,使用生成器表达式"""it = (len(x) for x in open('/tmp/my_file.txt'))"""打印的结果是generator"""print(it)"""使用内置的next函数取出生成器中的下一个值"""print(next(it))print(next(it))"""输出:100 57"""

10.尽量用enumerate取代range

from random import *random_bits = 0for i in range(64):    if randint(0, 1):        random_bits |= 1 << i        #print(random_bits)"""例子"""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 
"""迭代list需要索引的时候"""for i in range(len(flavor_list)):    flavor = flavor_list[i]    print('%d: %s' % (i + 1, flavor))
1: vanilla2: chocolate3: pecan4: strawberry
"""更好的办法是用enumerate"""for i, flavor in enumerate(flavor_list):    print('%d: %s' % (i + 1, flavor))
1: vanilla2: chocolate3: pecan4: strawberry
  • enumerate可以把各种迭代器包装成生成器。
  • 生成器每次产生一堆输出值,前者表示循环下标,后者表示从迭代器中的下一个序列的元素。
"""还可以指定enumerate函数开始计数时所用的值"""for i, flavor in enumerate(flavor_list, 1):    print('%d: %s' % (i, flavor))
1: vanilla2: chocolate3: pecan4: strawberry
原创粉丝点击