假设我有一个具有以下结构的Python字典:
data = {
"key_1": "some value",
"key_2": "some value",
"key_3": "",
"key_4": ""
}
所以,我想删除所有值为空字符串的键值。 我可以通过以下方式使用 python :
for key in list(data.keys()):
if data[key] == "":
del data[key]
或者我可以构建一本具有理解力的新词典:
new_ dict = {
key: value
for key, value in data.items()
if value != ""
}
两种解决方案都非常具有可读性,但哪个更有效,为什么?
del
在这两种情况下都表现不佳,但是当原始字典中有很多空白时,构建一个新的表现会更好。import time
def build_data():
return {f"{i}": f"{i}" for i in range(100000)} | {"blank":""}
def build_half_blank_data():
return {f"{i}": f"{i}" for i in range(50000)} | {f"{i}": "" for i in range(50000,100000)}
def del_method(data):
for key in list(data.keys()):
if data[key] == "":
del data[key]
return data
def build_method(data):
return {key: value for key, value in data.items() if value != ""}
data = build_data()
half_blank_data = build_half_blank_data()
start_time = time.time()
del_method(data)
print("---del_method + data %s seconds ---" % (time.time() - start_time))
start_time = time.time()
del_method(half_blank_data)
print("---del_method + half_blank %s seconds ---" % (time.time() - start_time))
start_time = time.time()
build_method(data)
print("---build_method + data %s seconds ---" % (time.time() - start_time))
start_time = time.time()
build_method(half_blank_data)
print("---build_method + half_blank %s seconds ---" % (time.time() - start_time))
---del_method + data 0.012892961502075195 seconds ---
---del_method + half_blank 0.012792825698852539 seconds ---
---build_method + data 0.012731075286865234 seconds ---
---build_method + half_blank 0.005828142166137695 seconds ---