Python 小点

  • for root, dir, file in os.walk(path) 遍历路径下的文件
  • os.path.join(xx, xx, ...) 合并多个路径,不同系统下通用
  • 跳出两层循环
for i in range(1,100):
    for j in range(1,100):
       break
    else:
       continue
    break
  • 关于

    • len()函数内部,它自动去调用该对象的__len__()方法
    • 获得一个对象的所有属性和方法,可以使用dir()函数
    • 配合getattr()setattr()以及hasattr(),可以直接操作一个对象的状态
    • @property装饰器负责把一个方法变成属性调用
    • __str__,返回自定义字符串,打印时使用
    • __iter__()方法返回一个迭代对象,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环
    • 像list那样按照下标取出元素,需要实现__getitem__()方法,按下标访问任意一项
  • zip()实现矩阵的行列互换

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表

>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  • eval()exec()的区别

    • eval()函数只能计算单个表达式的值,而exec()函数可以动态运行代码段。
    • eval()函数可以有返回值,而exec()函数返回值永远为None
    • 与之相对的,str()repr()
  • P = {s : {a : [] for a in range(3)} for s in range(4)}
    二维数组的字典实现

  • 使用两列数据创建字典

keys = ['1001', '1002', '1003']
values = ['骆昊', '王大锤', '白元芳']
d = dict(zip(keys, values))
print(d)
  • 与命令行的交互,参考
import argparse
parse = argparse.ArgumentParser()

parse.add_argument("--bool", help="Whether to pirnt sth")
parse.add_argument("--rate", type=float, default=0.01, help="initial rate")
parse.add_argument("--choice", choices=[0, 1], help="you can only input 0 or 1.")
parse.add_argument("--need", required=True, help="give it a value")

args = parse.parse_args()
if args.bool:
    print("bool: ", args.bool)
if args.rate:
    print("rate: ", args.rate)
if args.choice:
    print("choice: ", args.choice)
if args.need:
    print("need: ", args.need)

一般把可选参数最后add,不可选参数放前面add;在命令行里面输入代码时,程序会先赋值先add的参数

  • pop()remove()方法删除数组元素,这两个函数之间的区别在于前者返回已删除的值,而后者则不返回
  • 多进程需要在main函数中运行
  • The __str__() and __repr__() methods deal with how objects are presented as strings, so you’ll need to make sure you include at least one of those methods in your class definition. If you have to pick one, go with __repr__() because it can be used in place of __str__().
  • list前加*,将列表解开成独立的参数,用于传入函数;dict前加**,传入函数,key作为变量,value作为相应key的值
def myfunc(x, y, z):
    print(x, y, z)

tuple_vec = (1, 0, 1)
dict_vec = {'x': 1, 'y': 0, 'z': 1}

>>> myfunc(*tuple_vec)
1, 0, 1

>>> myfunc(**dict_vec)
1, 0, 1
  • [P1, P2, P3, ...Pn].sort(key=lambda x: (x.first_key, x.second_key, x.third_key, ...)) 主次关键字排序
  • 字典,setdefault()方法设置默认值,或者使用collections.defaultdict(type)
  • zip使用多个序列作为参数,然后返回元组的列表,将这些序列中的并排元素一一配对。当zip的多个参数长度不同时,zip会以最短序列的长度为准来截断所得到的元组
  • Python dictionaries check for equality and compare the hash value (even if they are of different types, as is the case for 1 and 1.0) to determine if two keys are the same.
  • namedtuples can be a great alternative to defining a class manually
# Why Python is Great: Namedtuples
# Using namedtuple is way shorter than
# defining a class manually:
>>> from collections import namedtuple
>>> Car = namedtuple('Car', 'color mileage')

# Our new "Car" class works as expected:
>>> my_car = Car('red', 3812.4)
>>> my_car.color
'red'
>>> my_car.mileage
3812.4

# We get a nice string repr for free:
>>> my_car
Car(color='red' , mileage=3812.4)

# Like tuples, namedtuples are immutable:
>>> my_car.color = 'blue'
AttributeError: "can't set attribute"
  • How to sort a Python dict by value
# (== get a representation sorted by value)

>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

# Or:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
  • merge two dictionaries
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}

>>> z
{'c': 4, 'a': 1, 'b': 3}
  • A lambda function is a small anonymous function.

    lambda arguments:expression

  • 一行方法

    • 快速漂亮的从文件打印出json数据, cat file.json | python -m json.tool
    • 脚本性能分析, python -m cProfile my_script.py
  • collections.OrderedDict , OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order, and iterating it gives the values in an arbitrary order.

  • collections.namedtuple, 用来创建一个tuple的子类,其可以通过属性名称访问tuple中的元素,便于理解

  • to be contunued

©️2020 CSDN 皮肤主题: 终极编程指南 设计师:CSDN官方博客 返回首页