Skip to content

Latest commit

 

History

History
167 lines (102 loc) · 5.21 KB

python.md

File metadata and controls

167 lines (102 loc) · 5.21 KB

Generate random string

import uuid
filename = str(uuid.uuid4())

Best way to generate random file names in Python

Delete dict key

my_dict.pop('key', None)

How to remove a key from a Python dictionary?

TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

change json.loads to json.load

python中读取json文件时报错,TypeError:the Json object must be str, bytes or bytearray,not ‘TextIOWrapper’

$ python -c "import math"
$ echo $?
0                                # math module exists in system

$ python -c "import numpy"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named numpy
$ echo $?
1                                # numpy module does not exist in system

About time

from datetime import date, timedelta

# Let's say it's Monday
today = date.today()
# datetime.date(2020, 6, 15)

last_week_start = today - timedelta(days=today.weekday()+7)
# today.weekday() = 0
# datetime.date(2020, 6, 8)
# last_week_start.weekday() = 0
# str(last_week_start) = '2020-06-08'

last_week_end = today - timedelta(days=today.weekday()+1)
# datetime.date(2020, 6, 14)
# last_week_end.weekday() = 6

datetime — Basic date and time types

Example of how to GZIP compress an existing file:

import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)
import os.path

# 检测文件是否存在:
os.path.isfile(fname)

if my_file.is_dir():
    # 指定的目录存在

# 如果要检测路径是一个文件或目录可以使用 exists() 方法:
if my_file.exists():
    # 指定的文件或目录存在

View moudel version

$ python -c "import sqlalchemy; print(sqlalchemy.__version__)"

How to check version of python modules?

sort list

sort: change original list

sorted: keep original list and return sorted list

Python列表排序方法reverse、sort、sorted详解

Ternary operator

b = a > 1? "Greater thant 1":"Less than or equal to 1"

python中的三元表达式(三目运算符)

Remove dulplicate items in list

python:对list去重

InsecureRequestWarning: Unverified HTTPS request is being made.

解决Python3 控制台输出InsecureRequestWarning的问题

compare list

print set(a) & set(b) # 交集, 等价于set(a).intersection(set(b))
print set(a) | set(b) # 并集, 等价于set(a).union(set(b))
print set(a) - set(b) # 差集,在a中但不在b中的元素, 等价于set(a).difference(set(b))
print set(b) - set(a) # 差集,在b中但不在a中的元素, 等价于set(b).difference(set(a))

[Python] 比较两个数组的元素的异同

Safe cast

def safe_cast(val, to_type, default=None):
    try:
        return to_type(val)
    except (ValueError, TypeError):
        return default

safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0

UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128)

cPickle.load(f) to cPickle.load(f, encoding='bytes')

TypeError: object of type 'zip' has no len()

net.SGD(training_data, 30, 10, 3.0, test_data=test_data) to net.SGD(list(training_data), 30, 10, 3.0, test_data=list(test_data))

NameError: name 'xrange' is not defined

replace xrange to range