20个python代码_有用的20个python代码段(4)
有用的20個(gè)python代碼段(4):
1、使用列舉獲取索引和值對(duì)
以下腳本使用列舉來(lái)迭代列表中的值及其索引。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、檢查對(duì)象的內(nèi)存使用
以下腳本可用來(lái)檢查對(duì)象的內(nèi)存使用。import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
3、合并兩個(gè)字典
在Python 2 中,使用update()方法合并兩個(gè)字典,而Python3.5 使操作過(guò)程更簡(jiǎn)單。
在給定腳本中,兩個(gè)字典進(jìn)行合并。我們使用了第二個(gè)字典中的值,以免出現(xiàn)交叉的情況。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、執(zhí)行一段代碼所需時(shí)間
下面的代碼使用time 軟件庫(kù)計(jì)算執(zhí)行一段代碼所花費(fèi)的時(shí)間。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知識(shí),請(qǐng)關(guān)注:Python自學(xué)網(wǎng)!!
總結(jié)
以上是生活随笔為你收集整理的20个python代码_有用的20个python代码段(4)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c++ 命名规则 private_【译】
- 下一篇: c#求三角形面积周长公式_此题求三角形的