栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

学Python最基本20个代码

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

学Python最基本20个代码

16.代码执行消耗时间

import time
start = time.time()
#代码块
num = 0
for i in range(1000000):
  num = i
#打印消耗时间
print("共消耗时间: ”,time.time() - start, "s")
运行结果
共消耗时间: 0. 07881712913513184 s

利用time()函数,在核心程序开始前记住当前时间点,然后在程序结束后计算当前时间点和核心程序开始前的时间差,可以帮助我们计算程序执行所消耗的时间。

17.检查对象的内存占用情况

import sys
str14 = "a"
str14_ 1 = "aaddf"
num14 = 32
print(sys.getsizeof (str14))
print(sys.getsizeof (num14))
print(sys.getsizeof(str14_ 1))
50
28
54

18.字典的合并

dict1 = {'a' :1, 'b':2}
dict2 = {'c' :3,'d':4}
#方法1
combined dict = {**dict1, **dict2}
print (combined_dict )
print("====================")
#方法2
dict1 = {'a' :1, 'b':2}
dict2 = {'c' :3, 'd':4}
dict1. update (dict2 )
print(dict1)
{'d': 4, 'a': 1, 'b': 2,'c': 3}
========================
{'d': 4, 'a': 1, 'b': 2,'c': 3}

在python3中,提供了新的合并字典的方式,如方法1所示,此外python3还保留了python2的合并字典的方式,如方法2所示。

19.随机采样

import random
str18 = "wewewe"
list18 = [1, 2, 4,5, 6]
n_samples = 3
print (random.samp1e(list18, n_ samples))
print (random.sample(str18, n_samples))
运行结果
[6, 4,5]
['e', 'e', 'w']

使用random. sample()函数,可以从一个序列中选择n_samples个随机且独立的元素。

20.检查唯一性。

str20=[1,2,3,4,5,6]
str20_1=[1,2,2,4,5, 6]
def ifUnque(seq):
if(len(seq) == len(set(seq))):
print("该列表中元素都是唯一的" )
else:
print("该列表中元素不都是唯一的" )
ifUnque(str20)
ifUnque(str20_ 1)
运行结果
该列表中元素都是唯一的
该列表中元素不都是唯一的

通过检查列表长度是否与set后的列表长度一致,来判断列表中的元素是否是独一无二的。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498975.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号