python个人学习笔记

阅读量: searchstar 2020-03-22 00:16:52
Categories: Tags:

语法

缩进应该使用4个空格而不是tab:https://peps.python.org/pep-0008/#tabs-or-spaces

for循环

0到9循环:

for i in range(10) :
	Statements

在交互式环境中(如命令行形式)后面要多打一个回车才开始运行

内置数据结构

List

教程:Python 列表(List)

a = [1, 2, 3, 4]

# 最后一个元素
# 4
a[-1]

# 从index为1的元素开始的所有元素
# [2, 3, 4]
a[1:]

# 以最后一个元素结尾(不含)的所有元素
# [1, 2, 3]
a[:-1]

# 以倒数第二个元素结尾(不含)的所有元素
# [1, 2]
a[:-2]

字典

Python教学: Python Dictionary完全教学一次搞懂

遍历

likes = {"color": "blue", "fruit": "apple", "pet": "dog"}
for key in likes:
    print(key)

输出:

color
fruit
pet
for (key, value) in likes.items():
    print(key, value)

输出:

color blue
fruit apple
pet dog

来源:https://realpython.com/iterate-through-dictionary-python/

其他

from dataclasses import dataclass
@dataclass
class A:
    a: int
    b: str
    c: float
li: list[A] = []
li.append(A(1, "2", 3.3))
li.append(A(2, "3", 4.4))
print(li)
# [<class '__main__.A'>, A(a=1, b='2', c=3.3), A(a=2, b='3', c=4.4)]
item = li[1]
print(item.c)
# 3.3
sorted(li, key = lambda item: item.c, reverse=True)

参考:https://stackoverflow.com/questions/35988/c-like-structures-in-python

完整教程:Python 面向对象

输入

输出

完整版:Python3 print 函数用法总结

输出为科学计数法

参考:https://blog.csdn.net/qq_45434742/article/details/102094577?fps=1&locationNum=2

print("%e" %111)
x = 111
print("%e" %x)
print("%e" %(111 + 111))
print("%e %e" %(x, 111 + 111))

不打印换行符

print('hello', end='')

打印到stderr

print('xxx', file=sys.stderr)

来源:https://stackoverflow.com/questions/5574702/how-do-i-print-to-stderr-in-python

指定分隔符打印数组

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

来源:https://stackoverflow.com/questions/22556449/print-a-list-of-space-separated-elements

format

打印到字符串。完整教程:https://note.nkmk.me/en/python-format-zero-hex/

这里介绍一些常用的。

保留3位小数:assert '{:.3f}'.format(2.3) == '2.300'

iterator

遍历:

it = iter([1, 2, 3])
while True:
    try:
        print(next(it))
    except StopIteration:
        break

for循环会自动catch StopIteration:

it = iter([1, 2, 3])
for x in it:
    print(x)

文件

python文件管理

python基础之写文件操作

切换到脚本所在目录

import sys
import os

abspath = os.path.abspath(sys.argv[0])
dname = os.path.dirname(abspath)
os.chdir(dname)

来源:https://stackoverflow.com/questions/1432924/python-change-the-scripts-working-directory-to-the-scripts-own-directory

打印到文件

使用printfile参数:

f = open(路径, 'w')
print('Average %f' %average, file=f)

来源:https://www.askpython.com/python/built-in-methods/python-print-to-file

Exceptions

Built-in Exceptions: https://docs.python.org/3/library/exceptions.html

常用的:

标准库

io

https://stackoverflow.com/questions/39823303/python3-print-to-string

时间

https://docs.python.org/3/library/datetime.html

datetime.datetime.fromtimestamp(1516332287)

也可以用time包:Python中时间与时间戳之间的转换

math

阶乘

10!

from math import *
factorial(10)

正则

https://docs.python.org/3/library/re.html

执行命令

简单执行命令

os.system('命令 参数...')

返回值是OS-dependant:https://stackoverflow.com/questions/6466711/what-is-the-return-value-of-os-system-in-python

可以用os.waitstatus_to_exitcode来将返回值变成exit code。如果正常退出,exit code就是0。

带参数命令

import subprocess
subprocess.run(['./executable', arg1, arg2])

文档:https://docs.python.org/3/library/subprocess.html#subprocess.run

可kill的命令

subprocess.Popen: https://stackoverflow.com/questions/43322201/how-to-kill-process-which-created-by-python-os-system

文档:https://docs.python.org/3/library/subprocess.html#popen-constructor

获取命令输出

python的popen函数

排序

sorted

对字典的key排序

x = {1: 2, 4: 3, 2: 1}
sorted(x)
[1, 2, 4]

对字典的值排序

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted(x.items(), key=lambda item: item[1])
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]

来源:https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value

shlex

可以用解析命令行参数的方式解析字符串。文档:https://docs.python.org/3/library/shlex.html

例子:

# https://stackoverflow.com/a/899314
import shlex
shlex.split('-o 1 --long "Some long string"')
['-o', '1', '--long', 'Some long string']

getopt

用法跟C语言的getopt差不多。

参考:Python 3 命令行参数

取整

四舍五入:round

向上取整:math.ceil

向下取整:math.floor

其他

三方库

dateutil

https://dateutil.readthedocs.io/en/stable/

pip3 install python-dateutil

可以实现时间减去月数等功能。

来源:https://thispointer.com/subtract-months-from-a-date-in-python/

pandas

官方文档:https://pandas.pydata.org/docs/

pandas数据框常用操作

Serias

官方文档:https://pandas.pydata.org/docs/reference/api/pandas.Series.html

常用成员函数

取平均:https://pandas.pydata.org/docs/reference/api/pandas.Series.mean.html

numpy

numpy学习笔记

json

字典和json字符串的转换

import json
# 使用tab进行缩进。
json.dumps(obj, indent='\t')

从文件读取

import json
json.load(open(路径))

但是遇到trailing comma会报错。可以用json5: https://stackoverflow.com/questions/23705304/can-json-loads-ignore-trailing-commas

pip3 install json5
import json5
json5.load(open(路径))

func_timeout

https://github.com/kata198/func_timeout

func_timeout的原理是开一个新的线程执行函数,timeout之后会raise exception,然后开一个新线程来join,所以timeout之后子线程可能会继续输出:

from func_timeout import func_timeout, FunctionTimedOut
import os

def test():
    for _ in range(0, 2):
        os.system('for i in $(seq 1 2); do sleep 1; echo test; done')

try:
    func_timeout(1.5, test)
except FunctionTimedOut:
    print('Timeout')
except Exception as e:
    # Code to handle any other exception
    print("An error occurred: {}".format(str(e)))

输出:

test
Timeout
test

如果需要等待join完成,需要使用StoppableThreadhttps://htmlpreview.github.io/?https://raw.githubusercontent.com/kata198/func_timeout/master/doc/func_timeout.StoppableThread.html

from func_timeout import FunctionTimedOut
from func_timeout.StoppableThread import StoppableThread
import subprocess

def test():
    try:
        for _ in range(0, 2):
            process = subprocess.Popen(['bash', '-c', 'for i in $(seq 1 2); do sleep 1; echo test; done'])
            # We must wait with timeout, otherwise it won't respond to external exceptions.
            # https://stackoverflow.com/a/631605/13688160
            process.wait(timeout=23333333)
    except FunctionTimedOut:
        try:
            # It seems to be okay even if process.wait is completed
            process.kill()
        except NameError:
            pass

def test_timeout(seconds):
    worker = StoppableThread(target=test)
    worker.start()
    worker.join(timeout=seconds)
    if worker.is_alive():
        print('Timeout')
        worker.stop(exception=FunctionTimedOut)
        worker.join()
    print('Joined')

test_timeout(1.5)
test_timeout(4.5)

输出:

test
Timeout
Joined
test
test
test
test
Joined

pip

安装指定版本:https://www.marsja.se/pip-install-specific-version-of-python-package/

requirements.txt: https://note.nkmk.me/en/python-pip-install-requirements/

有关

已知的问题

调用另一个文件里的函数不太方便: https://www.geeksforgeeks.org/python-import-module-from-different-directory/