python猫咪藏在哪个房间_python标准库学习笔记3

以下内容来自这里的学习。

类型判断

理论上动态语言不建议判断类型,不过python还是有提供判断的方法。

Python

import types

type(1) == types.IntType

isinstance(1, int)

1

2

3

4

importtypes

type(1)==types.IntType

isinstance(1,int)

第一种是使用types模块,第二种是使用内建的isinstance方法。

decimal

因为Java有BigInteger和BigDecimal,所以不会陌生。

Python

import decimal

decimal.getcontext().prec = 7 # set precision to 7, default is 28

decimal.Decimal(1) # create from int

decimal.Decimal('3.14') # create from string

decimal.Decimal(1) / decimal.Decimal(7)

1

2

3

4

5

6

importdecimal

decimal.getcontext().prec=7# set precision to 7, default is 28

decimal.Decimal(1)# create from int

decimal.Decimal('3.14')# create from string

decimal.Decimal(1)/decimal.Decimal(7)

默认decimal精度为28,可以通过getcontext()修改配置。带小数的建议使用字符串创建,否则你用decimal.Decimal(3.14)试试看。

分数

就是那种几分之几的分数。

Python

import fractions

fractions.Fraction(16, -10) # - 8/5

fractions.Fraction(decimal.Decimal('1.1')) # 11/10

fractions.gcd(60, 56) # 4

1

2

3

4

5

importfractions

fractions.Fraction(16,-10)# - 8/5

fractions.Fraction(decimal.Decimal('1.1'))# 11/10

fractions.gcd(60,56)# 4

fractions会帮你做约分,事实上这个库还有一个叫做gcd的函数。通过之前的decimal创建也是可以的。

随机数

Python

import random # or os.urandom, SystemRandom

random.random() # 0.0 <= x < 1.0

random.uniform(1, 10) # 1.0 <= x < 10.0

random.randint(1, 10) # [1, 10]

random.randrange(0, 101, 2) # even integer from 0 to 100

random.choice('abcdefghij') # choose a random element

random.shuffle([1, 2, 3, 4, 5, 6, 7]) # shuffle a list

random.sample([1, 2, 3, 4, 5, 6, 7], 3) # select three items

1

2

3

4

5

6

7

8

importrandom# or os.urandom, SystemRandom

random.random()# 0.0 <= x < 1.0

random.uniform(1,10)# 1.0 <= x < 10.0

random.randint(1,10)# [1, 10]

random.randrange(0,101,2)# even integer from 0 to 100

random.choice('abcdefghij')# choose a random element

random.shuffle([1,2,3,4,5,6,7])# shuffle a list

random.sample([1,2,3,4,5,6,7],3)# select three items

这块基本照搬标准库介绍的例子,因为我觉得每个方法都很有用。除了基础的随机数,还有典型的几种随机数应用。

operator

映射标准操作。个人暂时能想到使用的地方如下:

Python

import operator

reduce(operator.add, [1, 2, 3, 4], 0)

1

2

importoperator

reduce(operator.add,[1,2,3,4],0)

以上就是今天学习python标准库了解到的东西。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值