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、执行代码所需的时间
下面的代码使用timee 软件库计算执行代码所花费的时间。
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自学网!!