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

Python (210) 2023-06-02 04:05:33

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

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

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

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

2、检查对象的内存使用

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

importsys
num=21
print(sys.getsizeof(num))
#InPython2,24
#InPython3,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 软件库计算执行一段代码所花费的时间。

importtime
start_time=time.time()
#Codetocheckfollows
a,b=1,2
c=a+b
#Codetocheckends
end_time=time.time()
time_taken_in_micro=(end_time-start_time)*(10**6)
print("Timetakeninmicro_seconds:{0}ms").format(time_taken_in_micro)

更多Python知识,请关注:Python自学网!!

THE END

发表回复