常用的Python模块

目录

 

1、使用copy模块来复制

2、keyword模块记录了所有的关键字

3、用random模块获得随机数

4、用sys模块来控制Shell程序

5、用time模块来得到时间

6、用pickle模块来保存信息


1、使用copy模块来复制

>>> class Animal:
             def _init_(self, species, number_of_legs, color):
                    self.species = species
                    self.number_of_legs = number_of_legs
                    self.color = color

>>> harry = Animal()
>>> harry._init_('hippogriff', 6, 'pink')
>>> import copy
>>> harriet = copy.copy(harry)
>>> print(harry.species)
hippogriff
>>> print(harriet.species)
hippogriff


a、浅拷贝

my_animals[0].spcies = 'ghoul'

print(my_animals[0].species)

ghoul

print(more_animals[0].species)

ghoul

物种都变了是因为copy实际上只做了“浅拷贝”,也就是说他不会拷贝我们要拷贝的对象中的对象。在这里,它拷贝了主对象list对象,但是并没有拷贝其中的每个对象。因此我们得到的是一个新列表,但其中的对象不是新的,列表more_animals中还是那三个同样的对象。

b、 深拷贝

more_animals = copy.deepcopy(my_animals)

myanimals[0].species = 'wyrm'

print(my_animals[0].species)

wyrm

print(more_animals[0].spcies)

ghoul

在copy模块中的另一个函数deepcopy,则会创建被拷贝对象中的所有对象是拷贝。当我们用deepcopy来复制my_animals时,我们会得到一个新列表,它的内容是所有对象的拷贝。这样做的结果是,对于原来列表中Animal对象的改动不会影响到新列表。

2、keyword模块记录了所有的关键字

Python自身所用到的那些单词被称为关键字,比如if,else等。

iskeyword函数返回一个字符串是否是Python关键字

变量kwlist包含所有Python关键字的列表。

>>> import keyword
>>> print(keyword.iskeyword('if'))
True
>>> print(keyword.iskeyword('ozwald'))
False
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

3、用random模块获得随机数

a、randint函数在一个数字范围内随机挑选一个数字。

>>> print (random.randint(1,100))
60
>>> print(random.randint(100,1000))
102
>>> print(random.randint(1000,5000))
1536

猜数字游戏

>>> import random
>>> num = random.randint(1,100)
>>> while True:
    print('Guess a number between 1 and 100')
    guess = input()
    i = int(guess)
    if i == num:
        print('You guess right')
        break
    elif i < num:
        print('Try higher')
    elif i > num:
        print('Try lower')

b、用choice从列表中随机选取一个元素

>>> import random
>>> desserts = ['ice cream', 'pancakes', 'brownies', 'cookies', 'candy']
>>> print(random.choice(desserts))
cookies

c、用shuffle来给列表洗牌

>>> import random
>>> desseerts = ['ice cream', 'pancakes', 'brownies', 'cookies', 'candy']
>>> random.shuffle(desserts)
>>> print(desserts)
['brownies', 'candy', 'pancakes', 'ice cream', 'cookies']

shuffle函数用来给列表洗牌,把元素打乱。

4、用sys模块来控制Shell程序

a、用exit函数来退出shell程序

>>> import sys
>>> sys.exit()

b、从stdin对象读取

>>> import sys
>>> v = sys.stdin.readline()
He who laughs last thinks slowest
>>> print(v)
He who laughs last thinks slowest

c、用stdout对象来写入

>>> import sys
>>> sys.stdout.write('What does a fish say when it swims into a wall?Dam.')
What does a fish say when it swims into a wall?Dam.50

当write结束时,他返回他所写入的字符的个数。

5、用time模块来得到时间

>>> import time
>>> print(time.time())
1539761973.2906716

对time()的调用所返回的数字实际上是自1970年1月1日00:00:00AM以来的秒数。

def lots_of_numbers(max):

    t1 = time.time()

    for x in range(0, max):

        print(x)

    t2 = time.time()

print('it took %s seconds' %(t2-t1))

a、用asctime来转换日期

>>> import time
>>> print(time.asctime())
Wed Oct 17 16:34:40 2018

asctime以日期的元组为参数,并把它转换成更可读的形式。

>>> t = (2020, 2, 23, 10, 30, 48, 6, 0, 0)
>>> print(time.asctime(t))
Sun Feb 23 10:30:48 2020

b、用localtime来得到日期和时间

函数localtime把当前的日期和时间作为一个对象返回,其中的值大体与asctime的参数顺序一样。

>>> import time
>>> print(time.localtime())
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=17, tm_hour=16, tm_min=39, tm_sec=32, tm_wday=2, tm_yday=290, tm_isdst=0)

>>> t = time.localtime()
>>> year = t[0]
>>> month = t[1]
>>> print(year)
2018

c、用sleep来休息

但你想推迟或者让你的程序慢下来时,可以用sleep函数。

>>> for x in range(1, 61):
    print(x)
    time.sleep(1)

6、用pickle模块来保存信息

>>> import pickle
>>> game_data = {'a':'1','b':'2','c':'3'}
>>> save_file = open('save.dat', 'wb')

>>>pickle.dump(game.data, save_file)

>>>save_file.close()

>>>load_file = open('save.dat', 'rb')

>>>loaded_game_data = pickle.load(load_file)

>>>load_file.close()

print(loaded_game_file)

{...}

原文地址:https://www.cnblogs.com/strawqqhat/p/10602516.html