Python入门

2019-12-11  本文已影响0人  无心Y

数字

# Number() 标准数据类型 python3中无long类型
int(str, base=10) # 转换为整型
float(obj) # 转换为浮点数
bool(obj) # 调用obj.__nonezero__()内置方法,返回对象的布尔值
complex(str) # 转化为复数

str(obj) # 调用obj.__str__()方法 or repr(obj)
chr(num) # ascii值转字符  97 -> 'a'
ord(chr) # 字符转ascii值  'a' -> 97
+
-
*
** # 幂次 pow(n1, n2)
/  # python3中是浮点除
// # 整除,商部强制取整 1//2 = 0; 1.0//2 = 0.0
%  # 取余
~  # 按位取反
&  # 按位与
^  # 按位异或
|  # 按位或
<< # 左移
>> # 右移
# 十进制转其他
oct(64) # 转八进制 '0o100'
hex(64) # 转16进制 '0x40'
bin(64) # 转二进制 '0b1000000'

# 其他转十进制
int('64')
int('100', 8)
int('40', 16)
int('1000000', 2)
a=-5
b=-5
a is b # True
a=-6
b=-6
a is b # False
abs(number)          # 取绝对值         
divmod(n1, n2)       # 返回一个包含商和余数的元组(n1//n2, n1%n2)
pow(n1, n2, mod=1)   # 幂次运算(n1**n2%mod)
round(number[,base]) # 四舍五入,base决定保留小数点后几位
import math
import random
import decimal

math.ceil(x)      # 向上取整
math.floor(x)     # 向下取整
math.fabs(x)      # 绝对值
math.factorial(x) # 阶乘
math.hypot(x, y)  # sqrt(x*x+y*y)
math.pow(x, y)    # 幂次
math.sqrt(x)      # 开平方
math.log(x)       # 求自然对数
math.log10(x)     # 求10为底的对数
math.trunc(x)     # 取整
math.e
math.pi

random.random()       # range[0, 1.0)
random.uniform(a, b)   # range[a, b] a,b之间的随机浮点数
random.randint(a, b)   # range[a, b] a,b之间的随机整数
random.randrange([start=0], stop, [step=1]) # range序列中的随机数
random.choice(seq)     # seq中随机取一个元素
random.shuffle(seq)    # 随机打乱seq
random.sample(seq, n)  # seq中随机选取n个元素

"""
金融应用和其它需要精确十进制表达的场合,
控制精度
控制舍入以适应法律或者规定要求"""
>>> from decimal import Decimal
>>> Decimal('0.1') / Decimal('0.3')
Decimal('0.3333333333333333333333333333')

>>> from decimal import getcontext
>>> getcontext().prec = 4 #设置全局精度
>>> Decimal('0.1') / Decimal('0.3')
Decimal('0.3333')

字符串

符号 描述
%s 格式化字符串
%d 格式化整数
%f 格式化浮点数
%e 科学计数法格式化浮点数
%g %f和%e简写
string.capitalize() # 首字母大写
string.title() # 所有字符大写
string.upper()
string.lower()
string.center(width, fillchar)
string.expandtabs(tabsize=8) # 将string中tab转换为空格
string.count(str)
bytes.decode(encoding='utf-8')
string.encode(encoding='utf-8')
string.startswith(str)
string.endswith(str)
string.strip()  # 去除两端空格
string.find(str) # 包含返回开始的索引,不包含返回-1
string.index(str) # 不包含抛异常
string.replace(old, new, [max])
string.join(seq) 
seq.split(str)
string.isalpha() # 全是字母
string.isdigit() # 全是数字
string.isnumeric() # 全是数字
string.isalnum() # 全是数字和字母

列表

l = []
l = [1, 2, 'a']
l = list('hello')
l = 'a, b, c'.split(',')
l = [1, 2, 3]
l.append(4)
l.extends(['a', 'b', 1])
l.insert(0, 'loda')
l = [1, 2, 3]
l[0] = 'a'
l[:2] = ['a', 'b']
l = ['a', 2, 3]
del l[0]
l[:] = []
l.remove('a')  # 元素不存在报ValueError
l.pop()    # 删除并返回最后一个元素
l.pop(1)   # 删除并返回指定位置的元素
l = ['a', 'b', 'c']
l.index('a')   # 元素不存在报ValueError
l.count('a')
l = [2, 3, 1, 5]
l.sort([cmp], [key], [reverse=False]) # key为指定排序的键, 默认正序排列
sorted(seq, [key], [reverse])

l.reverse()
reversed(seq)
[ x*x for x in seq if x%2==0]
for index, value in enumerate(l):
    print(index, value)
outer = [1, 2, 3]
inner = [10, 20, 30]
l = [ x+y for x in outer for y in inner]

元组

t = ()
t = (1,)
t = tuple('hello')
x, y = (1, 2)

print('%s is %s years old.' % ('tom', 20))

def print_list(l):  # 传参,强制不改变原始序列
    t = tuple(l) 
    dosomething()

字典

d = {}
d = {'a': 1, 'b': 2}
d['c'] = 3

d = dict()
d = dict([('a', 1), ('b', 2)])
d = dict(a=1, b=2)
d = dict(zip(['a', 'b'], [1, 2]))

d = dict.fromkeys(['a', 'b'], 'default_value')

from copy import deepcopy
d1 = deepcopy(d)
if k in d:
    print(d.get(k))

for k in d:
    dosth()

for k, v in d.items():
    dosth()

for v in d.values():
    dosth()
d = {'a': 1, 'b': 2}
d['a'] = 2

d.update({'a': 2, 'c': 1})
d.update(a=1, b=2, d=4)
d = {'a': 1, 'b': 2, 'c': 3}
del d['a']

d.pop('b')

d.clear() #清空字典
d = {'b': 1, 'a': 4, 'c': 3}

sorted(d) # 返回按键正序排列的键列表

from operator import itemgetter
d = sorted(d.iteritems(), key=itemgetter(1), reverse=True) # 返回按照值倒序排列的键值对元组列表
switch = {
    'a': lambda x:x*2,
    'b': lambda x:x*3,
    'c': lambda x:x**x,
    'default': lambda x: x,
}
swtich.get('a', 'default')(2)

集合

s = set()
s = set([1, 2, 3])
s = set('hello')

f = frozenset()   # 不可修改
f = frozenset([1, 2, 'a', 'b'])
s = set([1, 2, 3])

# 成员判断
1 in s
4 not in s

# 添加
s.add(4)
s.upate(set([3, 4]))

# 删除
s.remove(1)    # 不安全,key不存在抛出KeyError
s.discard(1)   # 安全
s.pop(1)       # 不安全,删除并返回删除的元素

s.clear()
# 交集
s.intersection(b)
s&b

# 并集
s.union(b)
s|b

# 差集
s.difference(b)
s-b

# 对称差分
s.symmetric_difference(b)
s^b

# 关系判断
s.issubset(b)    # 子集
s.issuperset(b)  # 父集
{x for x in range(3)}
>>>set([0, 1, 2])

函数

def func(*arg, **kwargs):
    dosth
    return 0
def sum(a, b):    # a, b形参
    return a+b
sum(1, 2)         # 1, 2实参
def sum(a, b):    
    return a+b

sum(1, 2)    # a=1, b=2
sum(2, 1)    # a=2, b=1
def sum(a, b=0): # b为默认参数
    return a+b

sum(1)
sum(2, 1)
def print_seq(*seq):            # 序列
    for i in seq:
        print(i)

print_seq([1, 2, 3])

def print_kwargs(**kwargs):     # 字典
    for k, v in kwargs.items():
        print('{}, {}'.format(k, v))

print_kwargs(a=1, b=2)

内置函数

abs(-1)         # 1
divmod(10, 3)   # (3, 1)
pow(2, 4)       # 16
round(2.56)     # 2.0
round(2.436, 2) # 2.44
min([1, 2, 3])  # 1
max([1, 2, 3])  # 3
l = [1, 2, 3]
len(l)      # 3
range(3)    # [0, 1, 2]
xrange(3)   # xrange obj
callable(obj)    # 对象是否可调用
cmp(x, y)        # x>y 返回1;x==y 返回0;x<y 返回-1
isinstance(obj, type)
type(obj)
chr(num)
ord(char)
str(obj)
repr(obj)

int(obj)
float(obj)
bool(obj)
complex(str)
oct(10)    # '0o12'
hex(20)    # '0x14'
bin(10)    # '0b1010'

int('0o12', 8)   # 10
int('0x14', 16)  # 20
int('0b1010', 2) # 10
list(seq)
tuple(seq)
dict(seq)
set(seq)
# 使用func作用于list中每一项,返回为函数返回值为True的所有项
filter(func, list)

# 使用map作用于list中的每一项,返回列表
map(func, list[,list])

# 选取seq中的前两项传参给func, 函数的返回和下一项继续传参给func,直到最后
reduce(func, seq)

# 返回元组列表
zip(list1, list2, [list])

文件处理

f_obj = open(filename, mode='r', buffering=-1)
file.read(size=-1)          # 从文件中读取size个字节,默认读取全部
file.readline(size=-1)      # 读取并返回一行,包含换行符
file.readlines(sizeint=0)   # 读取所有行,并返回列表

file.write(str)             # 向文件中写入字符串
file.writelines(seq)        # 向文件中写入行列表

file.seek(offset, whence=0) # 移动文件指针,whence=0 开始, 1 当前, 2末尾
file.tell()                 # 获取文件指针的位置
file.truncate(size)         # 从当前位置开始,截取size个字节
file.close()                # 关闭文件
file.fileno()               # 返回文件描述符
file.flush()                # 刷新文件内部缓存
file.isatty()               # 判断file是否是类tty设备
file.next()                 # 返回文件下一行
# 文件读取
with open(file) as f:
    for line in f:
        line = line.strip()

# pickle 存储对象
import pickle

d = {1: 'a', 2: 'b'}
with open('data.pkl', 'wb') as f:
    pickle.dump(d, f)

with open('data.pkl', 'rb') as f:
    data = pickle.load(f)
    print(data)

# struct 打包和解析二进制数据
import struct

with open('data.bin', 'wb') as f:
    data = struct.pack('hhl', 1, 2, 3)
    f.write(data)

with open('data.bin', 'rb') as f:
    data = f.read()
    data = strunt.unpack('hhl', data)
    print(data)

日期处理

# datetime
import datetime

now = datetime.datetime.now()
print(now)
>>>2019-12-11 11:56:28.930000

# date
date = datetime.datetime.now().date()
print(date)
>>>2019-12-11

# timestamp
import time

print(time.time())
>>>1576036503.16

# time tuple
import time
print(time.localtime())
>>>time.struct_time(tm_year=2019, tm_mon=12, tm_mday=11, tm_hour=11, tm_min=55, tm_sec=43, tm_wday=2, tm_yday=345, tm_isdst=0)

# string
import datetime

print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
>>>2019-12-11 11:56:28
import datetime

# 获取当前时间
datetime.datetime.now()

# 获取当前日期
datetime.date.today()

# 获取前/后 N天
datetime.datetime.now() + datetime.timedelta(days=1)
datetime.datetime.now() - datetime.timedelta(days=1)

# 获取当天开始/结束时间
datetime.datetime.combine(datetime.date.today(), datetime.time.min)
datetime.datetime.combine(datetime.date.today(), datetime.time.max)

# 获取本周/月/上月最后一天
today = datetime.date.today()
sunday = today + datetime.timedelta(6 - today.weekday())

import calendar

_, last_day = calendar.monthrange(today.year, today.month)
last_day = datetime.data(year=today.year, month=today.month, day=last_day)

first_day = datetime.date(year=today.year, month.today.month, day=1)
last_month = first_day - datetime.timedelta(days=1)

import datetime
import time
# datetime <=> string
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
datetime.datetime.strptime('2019-12-11 11:56:28', '%Y-%m-%d %H:%M:%S')

# datetime <=> timestamp
now = datetime.datetime.now()
timestamp = time.mktime(now.timetuple())

datetime.datetime.fromtimestamp(time.time())

# datetime <=> timetuple
timetuple = now.timetuple()

now = datetime.datetime.fromtimestamp(time.mktime(time.localtime()))
上一篇 下一篇

猜你喜欢

热点阅读