【发布时间】:2021-03-21 12:58:22
【问题描述】:
Python 新手,正在尝试学习如何使用字典,但老实说,你没有看到重点,你被限制为 2 对,而如果我只是用元组创建一个列表,我会获得更大的灵活性
在下面的代码中,我列出了超级英雄,您可以在其中查找 姓名(蝙蝠侠)、身份(布鲁斯·韦恩)或宇宙(DC)
不能在字典上做到这一点(你只能对 2 个)那么我为什么需要字典呢?
Superheroes = [('Batman','Bruce Wayne','DC'),('Spiderman','Peter Parker','Marvel'),('Superman','Clark Kent','DC'),('Ironman','Tony Stark','Marvel'),('Green Arrow','Oliver Queen','DC')]
user_selection = input()
for (name,identity,universe) in Superheroes:
if name==user_selection or identity == user_selection or universe == user_selection:
print('Hero:' + name + '\nSecret Identity:' + identity + '\nUniverse:'+ universe)
else:
continue
【问题讨论】:
-
因为字典不需要顺序搜索。
-
大多数字典的使用不需要像这样搜索所有字段。
-
好吧,但这也不对吗?
-
您正在进行顺序搜索。
-
@falconflyer75:此循环检查
Superheroes中的每个条目;如果您有 5000 万个条目,那就是 1.5 亿次检查(5000 万个条目中的每个条目进行三个测试)。可以制作三个collections.defaultdict(list),由每个字段键入(一个带有name键,一个带有identity键,一个带有universe键),附加lists 匹配值,减少检查次数到 3,每个dict一个,以便宜地获取所有匹配条目。在这种情况下,数据库可能会更好地工作,并允许更复杂的查询,并具有与dicts 相似的性能优势。
标签: python list dictionary search tuples