简体   繁体   English

优化创建列表字典

[英]Optimize creating a dictionary of list

I have a following class 我有一个下课

class Test:
    self.value = 0
    self.name = ''

I have million of records and i want to sort only selective records based on their name . 我有数百万条记录,我只想根据其name对选择性记录进行排序。 I have created a separate list called whitelist_names . 我创建了一个单独的列表,称为whitelist_names The way i am making the dictionary-list object is like that 我制作字典列表对象的方式是这样的

'''input_value and input_name are being feed from a file-read'''
map_list = {}

t = Test(input_value, input_name)

if t.input_name in whitelist_names:
    name_list = []
    if t.input_name in map_list:
        name_list = map_list[t.input_name]
    name_list.append(t)
    map_list[t.input_name] = name_list

The above piece of code is taking forever. 上面的代码将永远存在。 I am new to python so just wanted to make sure if i am doing it right or not. 我是python的新手,所以只想确保我是否做对了。

Well as you're checking if a certain name is in a list it is quite logical that its taking a while. 在检查某个名称是否在列表中的过程中,花点时间是很合逻辑的。 If the white listed names are all unique you could use a set instead of a list. 如果白色列出的名称都是唯一的,则可以使用集合而不是列表。 Set comprehension is a lot faster than list. 集合理解比列表快很多。

Furthermore, instead of implementing a class to hold a name and the amount of times it showed up, I would suggest you use a dictionary. 此外,我建议您使用词典,而不是实现一个用于容纳名称和名称显示次数的类。 As dictionaries are implemented as hashmaps the check if the entry exist is very fast. 由于字典被实现为哈希映射,因此检查条目是否存在的速度非常快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM