存储一组四个(或更多)值的最佳数据结构是什么?

2024-04-26 03:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有下面的variables及其对应的values,它表示一个record

name = 'abc'
age = 23
weight = 60
height = 174

请注意,value可以是不同的typesstringintegerfloat,对任何其他对象的引用等)。

将会有很多records(至少100000)。当这四个variables(实际上是它的values)放在一起时,每个record都将是unique。换句话说,不存在record,所有4values都是相同的。

我试图在Python中找到一个有效的数据结构,它将允许我(存储和)检索records基于log(n)时间复杂性中的任何一个variables

例如:

def retrieve(name=None,age=None,weight=None,height=None) 
    if name is not None and age is None and weight is None and height is None:
        /* get all records with the given name */
    if name is None and age is not None and weight is None and height is None:
        /* get all records with the given age */
    ....
    return records

调用retrieve的方式如下:

retrieve(name='abc') 

上面应该返回[{name:'abc', age:23, wight:50, height=175}, {name:'abc', age:28, wight:55, height=170}, etc]

retrieve(age=23) 

上面应该返回[{name:'abc', age:23, wight:50, height=175}, {name:'def', age:23, wight:65, height=180}, etc]

而且,我可能需要在以后的记录中再添加一个或两个variables。例如,说,sex = 'm'。因此,retrieve函数必须是可伸缩的。

简而言之:在Python中是否有一个数据结构允许storing a record具有n个数的columns(姓名、年龄、性别、体重、身高等)和retrieving records基于logarithmic(或理想情况下的constant - O(1)查找时间)复杂性中的任何一个?


Tags: andnamenone数据结构ageisvariablesrecord
3条回答

Python中没有一个单独的数据结构可以实现您想要的所有功能,但是使用这些数据结构的组合来实现您的目标并相当有效地做到这一点是相当容易的。

例如,假设您的输入是名为employees.csv的逗号分隔值文件中的以下数据,其中的字段名由第一行定义:

name,age,weight,height
Bob Barker,25,175,6ft 2in
Ted Kingston,28,163,5ft 10in
Mary Manson,27,140,5ft 6in
Sue Sommers,27,132,5ft 8in
Alice Toklas,24,124,5ft 6in

以下是工作代码,说明如何将此数据读取并存储到记录列表中,并自动创建单独的查找表,以查找与每个记录的字段中包含的值相关联的记录。

记录是由namedtuple创建的类的实例,这非常节省内存,因为每个类都缺少类实例通常包含的__dict__属性。使用它们可以使用点语法(如record.fieldname)按名称访问每个字段。

查找表是defaultdict(list)实例,它提供类似字典的O(1)平均查找时间,并且允许每个值关联多个值。因此,查找键是要查找的字段值的值,与之关联的数据将是存储在具有该值的employees列表中的Person记录的整数索引列表,因此它们都相对较小。

请注意,类的代码完全是数据驱动的,因为它不包含任何硬编码字段名,而这些字段名都是从csv数据输入文件的第一行读取的。当然,在使用实例时,所有的retrieve()方法调用都必须提供有效的字段名。

更新

修改为在第一次读取数据文件时不为每个字段的每个唯一值创建查找表。现在,retrieve()方法“惰性地”只在需要时创建它们(并保存/缓存结果以供将来使用)。也被修改为在Python2.7+中工作,包括3.x

from collections import defaultdict, namedtuple
import csv

class DataBase(object):
    def __init__(self, csv_filename, recordname):
        # Read data from csv format file into a list of namedtuples.
        with open(csv_filename, 'r') as inputfile:
            csv_reader = csv.reader(inputfile, delimiter=',')
            self.fields = next(csv_reader)  # Read header row.
            self.Record = namedtuple(recordname, self.fields)
            self.records = [self.Record(*row) for row in csv_reader]
            self.valid_fieldnames = set(self.fields)

        # Create an empty table of lookup tables for each field name that maps
        # each unique field value to a list of record-list indices of the ones
        # that contain it.
        self.lookup_tables = {}

    def retrieve(self, **kwargs):
        """ Fetch a list of records with a field name with the value supplied
            as a keyword arg (or return None if there aren't any).
        """
        if len(kwargs) != 1: raise ValueError(
            'Exactly one fieldname keyword argument required for retrieve function '
            '(%s specified)' % ', '.join([repr(k) for k in kwargs.keys()]))
        field, value = kwargs.popitem()  # Keyword arg's name and value.
        if field not in self.valid_fieldnames:
            raise ValueError('keyword arg "%s" isn\'t a valid field name' % field)
        if field not in self.lookup_tables:  # Need to create a lookup table?
            lookup_table = self.lookup_tables[field] = defaultdict(list)
            for index, record in enumerate(self.records):
                field_value = getattr(record, field)
                lookup_table[field_value].append(index)
        # Return (possibly empty) sequence of matching records.
        return tuple(self.records[index]
                        for index in self.lookup_tables[field].get(value, []))

if __name__ == '__main__':
    empdb = DataBase('employees.csv', 'Person')

    print("retrieve(name='Ted Kingston'): {}".format(empdb.retrieve(name='Ted Kingston')))
    print("retrieve(age='27'): {}".format(empdb.retrieve(age='27')))
    print("retrieve(weight='150'): {}".format(empdb.retrieve(weight='150')))
    try:
        print("retrieve(hight='5ft 6in'):".format(empdb.retrieve(hight='5ft 6in')))
    except ValueError as e:
        print("ValueError('{}') raised as expected".format(e))
    else:
        raise type('NoExceptionError', (Exception,), {})(
            'No exception raised from "retrieve(hight=\'5ft\')" call.')

输出:

retrieve(name='Ted Kingston'): [Person(name='Ted Kingston', age='28', weight='163', height='5ft 10in')]
retrieve(age='27'): [Person(name='Mary Manson', age='27', weight='140', height='5ft 6in'),
                     Person(name='Sue Sommers', age='27', weight='132', height='5ft 8in')]
retrieve(weight='150'): None
retrieve(hight='5ft 6in'): ValueError('keyword arg "hight" is an invalid fieldname')
                           raised as expected

给定http://wiki.python.org/moin/TimeComplexity这个如何:

  • 为你感兴趣的每一列都准备一本字典-AGENAME,等等
  • 使字典的键(AGENAME)成为给定列(35或“m”)的可能值。
  • 有一个表示一个“集合”值的列表列表,例如VALUES = [ [35, "m"], ...]
  • 使列字典(AGENAME)的值成为VALUES列表中的索引列表。
  • VALUES中有一个字典,它将列名映射到列表中的索引,这样您就知道第一列是年龄,第二列是性别(您可以避免这一点,并使用字典,但它们引入了大内存footrpint,并且有超过100K个对象,这可能是问题,也可能不是问题)。

然后retrieve函数可以如下所示:

def retrieve(column_name, column_value):
    if column_name == "age":
        return [VALUES[index] for index in AGE[column_value]]      
    elif ...: # repeat for other "columns"

那么,这就是你得到的

VALUES = [[35, "m"], [20, "f"]]
AGE = {35:[0], 20:[1]}
SEX = {"m":[0], "f":[1]}
KEYS = ["age", "sex"]

retrieve("age", 35)
# [[35, 'm']]

如果需要词典,可以执行以下操作:

[dict(zip(KEYS, values)) for values in retrieve("age", 35)]
# [{'age': 35, 'sex': 'm'}]

不过,字典在内存方面还是有点重,所以如果你能列出一些值,可能会更好。

字典和列表检索平均都是O(1)-字典的最坏情况是O(n)-所以这应该相当快。保持这一点会有点痛苦,但不会太痛苦。要“写”,您只需附加到VALUES列表,然后将VALUES中的索引附加到每个字典。

当然,最好的方法是对实际的实现进行基准测试,并寻找潜在的改进,但希望这是有意义的,并能让您继续:)

编辑:

请注意,正如@moooeeep所说,只有当您的值是可散列的,因此可以用作字典键时,这才起作用。

Is there a data structure in Python which will allow storing a record with n number of columns (name, age, sex, weigh, height, etc) and retrieving records based on any (one) of the column in logarithmic (or ideally constant - O(1) look-up time) complexity?

不,没有。但是您可以尝试在每个值维度一个字典的基础上实现一个。当然,只要你的值是散列的。如果为记录实现自定义类,则每个字典都将包含对相同对象的引用。这会帮你省点内存。

相关问题 更多 >