20个python代码_有用的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)
更多Python知識,請關注:Python自學網!!
總結
以上是生活随笔為你收集整理的20个python代码_有用的20个python代码段(4)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++ 命名规则 private_【译】
- 下一篇: python q切换指定目录_Pytho