流畅的python和cookbook学习笔记(五)

时间:2021-08-02 02:28:26

1.随机选择

  python中生成随机数使用random模块。

  1.从序列中随机挑选元素,使用random.choice()

>>> import random
>>> values = [1, 2, 3, 4, 5, 6]
>>> random.choice(values)
3
>>> random.choice(values)
3
>>> random.choice(values)
1
>>> random.choice(values)
1
>>> random.choice(values)
4

  2.取出指定个数的元素,使用random.sample()

>>> random.sample(values, 2)
[
1, 4]
>>> random.sample(values, 2)
[
3, 5]
>>> random.sample(values, 3)
[
5, 3, 2]
>>> random.sample(values, 3)
[
1, 3, 2]

  3.打乱序列的顺序,可以用来洗牌,使用random.shuffle()

>>> random.shuffle(values)
>>> values
[
2, 4, 5, 3, 6, 1]
>>> random.shuffle(values)
>>> values
[
2, 6, 5, 4, 3, 1]

  4.生成随机整数,使用random.randint()

>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
10
>>> random.randint(1, 10)
5

  5.生成 0 到 1 之间的浮点数,使用random.random()

>>> random.random()
0.31720220264500265
>>> random.random()
0.8230452349376671
>>> random.random()
0.09307172325744872

  6.生成随机比特位的整数,使用random.getrandbits()

>>> random.getrandbits(200)
859899606181938256764615251875627706548045135119258688489931
>>> random.getrandbits(200)
582401031226834278134883678914218487507678688169321631685078

 

2.时间的转换

  1.python中使用datetime模块来转换时间。

>>> from datetime import timedelta
>>> a = timedelta(days = 2, hours = 6)
>>> b = timedelta(hours = 4.5)
>>> c = a + b
>>> c.days
2
>>> c.seconds
37800
>>> c.seconds / 3600
10.5
>>> c.total_seconds() / 3600
58.5

  表示特定的日期和时间。

>>> from datetime import datetime
>>> a = datetime(2017, 9, 8)
>>> print(a + timedelta(days=2))
2017-09-10 00:00:00
>>> b = datetime(2017, 9, 22)
>>> d = b - a
>>> d.days
14
>>> now = datetime.today()
>>> print(now)
2017-09-08 20:09:56.904169
>>> print(now + timedelta(minutes=10))
2017-09-08 20:19:56.904169

  2.使用dateutil模块,可以处理不同月份中的天数。datetime不能处理月份。

>>> from dateutil.relativedelta import relativedelta
>>> a = datetime(2017, 9, 8)
>>> a + relativedelta(months=1)
datetime.datetime(
2017, 10, 8, 0, 0)
>>> a + relativedelta(months=4)
datetime.datetime(
2018, 1, 8, 0, 0)
>>> b = datetime(2017, 11, 11)
>>> d = b - a
>>> d
datetime.timedelta(
64)
>>> d = relativedelta(b, a)
>>> d
relativedelta(months
=+2, days=+3)
>>> d.months
2
>>> d.days
3

  3.把字符串转换为时间,使用datetime.strptime(),把时间转化为字符串使用datetime.strftime()

>>> from datetime import datetime
>>> text = '2017-9-8'
>>> y = datetime.strptime(text, '%Y-%m-%d')
>>> z = datetime.now()
>>> diff = z - y
>>> diff
datetime.timedelta(0,
73494, 826144)
>>> y
datetime.datetime(
2017, 9, 8, 0, 0)
>>> z
datetime.datetime(
2017, 9, 8, 20, 24, 54, 826144)
>>> nice_z = datetime.strftime(z, '%A %B %d %Y')
>>> nice_z
'Friday September 08 2017'