有用的20个python代码段(4)

478次阅读
没有评论

有用的20个python代码段(4)

有用的20个python代码段(4):

1、使用列举获取索引和值对

以下脚本使用列举来迭代列表中的值及其索引。

my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
    print('{0}: {1}'.format(index, value))
# 0: a
# 1: b
# 2: c
# 3: d
# 4: e

2、检查对象的内存使用

以下脚本可用来检查对象的内存使用。

import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28

3、合并两个字典

在Python 2 中,使用update()方法合并两个字典,而Python3.5 使操作过程更简单。

在给定脚本中,两个字典进行合并。我们使用了第二个字典中的值,以免出现交叉的情况。

dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)
# Output
# {'apple': 9, 'banana': 4, 'orange': 8}

4、执行一段代码所需时间

下面的代码使用time 软件库计算执行一段代码所花费的时间。

import time
start_time = time.time()
# Code to check follows
a, b = 1,2
c = a+ b
# Code to check ends
end_time = time.time()
time_taken_in_micro = (end_time- start_time)*(10**6)
print(" Time taken in micro_seconds: {0} ms").format(time_taken_in_micro)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-15发表,共计857字。
新手QQ群:570568346,欢迎进群讨论 Python51学习