用列表+迭代和用字典哪个更高效?
list1 = [["牛奶",5],["面包",20],["水",7]]f = input("请输入要查找单价的物品:")
for i in list1:
if i == f:
print(i,"元")
break
else:
print("未查寻到该物品!")
dict1 = {"牛奶":5,"面包":20,"水":7}
f = input("请输入要查找单价的物品:")
try:
print(dict1,"元")
except:
print("未查寻到该物品!")
这两种哪个效率高?
1、用列表+for循环
2、用字典 本帖最后由 歌者文明清理员 于 2023-3-25 16:07 编辑
2 效率高,因为:
# -*- coding:utf-8 -*-
from time import perf_counter_ns
def check_time(func):
def new(*args, **kwargs):
start = perf_counter_ns()
func(*args, **kwargs)
end = perf_counter_ns()
diff = end - start
return diff
return new
@check_time
def listfor():
list1 = [["牛奶", 5], ["面包", 20], ["水", 7]]
f = "水"
for i in list1:
if i == f:
print(i, "元")
break
else:
print("未查寻到该物品!")
@check_time
def dict():
dict1 = {"牛奶": 5, "面包": 20, "水": 7}
f = "水"
try:
print(dict1, "元")
except:
print("未查寻到该物品!")
def print(*args, **kwargs):
pass
t1 = 0
t2 = 0
count = int(input('测试次数:'))
for i in range(count):
t1 += listfor()
for i in range(count):
t2 += dict()
del print
a1 = t1 / count
a2 = t2 / count
print('Unit: 纳秒')
print('list+for:')
print('- total', t1)
print('- average', a1)
print('dict:')
print('- total', t2)
print('- average', a2)
自己试试
我的结果是:
测试次数:1000000
Unit: 纳秒
list+for:
- total 357286400
- average 357.2864
dict:
- total 246054500
- average 246.0545
@isdkz @liuhongrun2022 @sfqxx @Mike_python小 @wp231957 @zhangjinxuan 字典是哈希,列表是线性表,肯定是哈希更优一些 歌者文明清理员 发表于 2023-3-25 16:05
2 效率高,因为:
谢谢 zhangjinxuan 发表于 2023-3-25 16:14
字典是哈希,列表是线性表,肯定是哈希更优一些
谢谢
页:
[1]