20.将两个列表转换成一个词典
以下方法可将两个列表转换成一个词典。
def to_dictionary( keys, values):returndict(zip( keys, values))keys= [ "a", "b", "c"]values= [ 2, 3, 4]print(to_dictionary( keys, values)) # {'a': 2, 'c': 4, 'b': 3}
21.使用枚举
以下方法将字典作为输入,然后仅返回该字典中的键。
list = [ "a", "b", "c", "d"]forindex, element inenumerate( list):print( "Value", element, "Index ", index,)# ( 'Value', 'a', 'Index ', 0)# ( 'Value', 'b', 'Index ', 1)#( 'Value', 'c', 'Index ', 2)# ( 'Value', 'd', 'Index ', 3)
22.计算所需时间
以下代码段可用于计算执行特定代码所需的时间。
import timestart_time = time.timea = 1b = 2c = a + bprint(c) #3end_time = time.timetotal_time = end_time - start_timeprint("Time: ", total_time)# ('