guopengfa
发布于 2022-04-25 / 2534 阅读 / 0 评论 / 0 点赞

Python tips

# fill zero of number
>>>a = '1'
>>>print(a)
1
>>>b = '1'.zfill(2*4)
>>>print(b)
00000001

# reverse sequence
>>>a = [0, 1, 2, 3, 4, 5]
>>>print(a[::-1])
[5, 4, 3, 2, 1, 0]

# append two list into one list method1
>>>a, b = [1, 2], [3, 4]
>>>a + b  # method one
>>>a.extend(b)  # method two: append b elements into a

# str to variable
>>>eval('[1, 2, 3, 4]')
>>>[1, 2, 3, 4]

# reversed list or str
>>>reversed([1, 2, 3, 4])
>>>[4, 3, 2, 1]
>>>''.join(reversed('str1'))
>>>'1rts'

# filter max by key a from dictionary list
>>>list1 = [{'a': 10, 'b': 20}, {'a': 15, 'b': 22}, {'a': 1, 'b': 50}, {'a': 3, 'b': 36}]
>>>max(list1, key=lambda x: x['a'])
>>>{'a': 15, 'b': 22}

>>>You can use below function to check object if has attribute
hasattr(emp1, 'age')    # 如果存在 'age' 属性返回 True。
getattr(emp1, 'age')    # 返回 'age' 属性的值
setattr(emp1, 'age', 8) # 添加属性 'age' 值为 8
delattr(emp1, 'age')    # 删除属性 'age'
>>>import os
>>>hasattr(os, 'age')
>>>False
>>>hasattr(os, 'chmod')
>>>True
>>>

>>> pip install requirements.txt --no-deps  # 忽略依赖包,直接安装主体

>>>all([True, True, False])  # 所有为True才为True,否则False
>>>False

>>>any([True, True, False])  # 任意其中有True才为True,否则False
>>>True

评论