
有用的20个python代码段(4):
1、使用列举获取索引和值对
以下脚本使用列举来迭代列表中的值及其索引。
1 2 3 4 5 6 7 8 | 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、检查对象的内存使用
以下脚本可用来检查对象的内存使用。
1 2 3 4 5 | import sys
num = 21
print (sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
|
3、合并两个字典
在Python 2 中,使用update()方法合并两个字典,而Python3.5 使操作过程更简单。
在给定脚本中,两个字典进行合并。我们使用了第二个字典中的值,以免出现交叉的情况。
1 2 3 4 5 6 | 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 软件库计算执行一段代码所花费的时间。
1 2 3 4 5 6 7 8 9 | 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)
|
更多Python知识,请关注:Python自学网!!