代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

创建向量向量空映射的方法

  •  1
  • Cheok Yan Cheng  · 技术社区  · 15 年前

    我有下面的C++代码

    std::map<std::string, std::vector<std::vector<std::vector<double> > > > details
    details["string"][index][index].push_back(123.5);
    

    我能知道什么是蟒蛇来声明向量向量的空映射吗?P

    我试着要

    self.details = {}
    self.details["string"][index][index].add(value)
    

    我得到了

    KeyError: 'string'
    
    4 回复  |  直到 13 年前
        1
  •  3
  •   user470379    15 年前

    最好的方法可能是对外部容器使用dict,其中字符串用于键映射到内部字典,元组(向量索引)映射为双精度:

     d = {'abc': {(0,0,0): 1.2, (0,0,1): 1.3}}
    

    它可能比实际嵌套列表效率更低(至少时间效率更低,实际上空间效率更高),但我更容易访问:

    >>> d['abc'][0,0,1]
    1.3
    

    编辑

    正在添加密钥:

    d = {} #start with empty dictionary
    d['abc'] = {} #insert a new string key into outer dict
    d['abc'][0,3,3] = 1.3 #insert new value into inner dict
    d['abc'][5,3,3] = 2.4 #insert another value into inner dict
    d['def'] = {} #insert another string key into outer dict
    d['def'][1,1,1] = 4.4
    #...
    >>> d
    {'abc': {(0, 3, 3): 1.3, (5, 3, 3): 2.4}, 'def': {(1, 1, 1): 4.4}}
    

    或者,如果使用python>=2.5,则更优雅的解决方案是使用 defaultdict :它的工作方式与普通字典一样,但可以为不存在的键创建值。

    import collections
    d = collections.defaultdict(dict)   #The first parameter is the constructor of values for keys that don't exist
    d['abc'][0,3,3] = 1.3
    d['abc'][5,3,3] = 2.4
    d['def'][1,1,1] = 4.4
    #...
    >>> d
    defaultdict(<type 'dict'>, {'abc': {(0, 3, 3): 1.3, (5, 3, 3): 2.4}, 'def': {(1, 1, 1): 4.4}})
    
        2
  •  3
  •   C. K. Young    15 年前

    python是一种动态(潜在类型)语言,所以在python语言中没有“矢量矢量图”(或“列表列表的dict”)。dict只是dict,可以包含任何类型的值。空的口述很简单: {}

        3
  •  0
  •   anijhaw    15 年前

    创建包含嵌套列表的dict,Inturn包含嵌套列表

    dict1={'a':[[2,4,5],[3,2,1]]}
    
    dict1['a'][0][1]
    4
    
        4
  •  0
  •   Paul Rigor    13 年前

    使用collections.defaultdict,可以尝试下面的lambda技巧。请注意,在酸洗这些对象时会遇到问题。

    from collections import defaultdict
    
    # Regular dict with default float value, 1D
    dict1D = defaultdict(float)
    val1 = dict1D["1"] # string key type; val1 == 0.0 by default
    
    # 2D
    dict2D = defaultdict(lambda: defaultdict(float))
    val2 = dict2D["1"][2] # string and integer key types; val2 == 0.0 by default
    
    # 3D
    dict3D = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
    val3 = dict3D[1][2][3] # val3 == 0.0 by default
    
    # N-D, arbitrary nested defaultdicts
    dict4D = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(str))))
    val4 = dict4D["abc"][10][9][90] # val4 == '' by default
    

    您基本上可以嵌套任意多个这些默认dict集合类型。另外,请注意,它们的行为类似于常规的Python字典,可以采用常见的键类型(不可变和哈希)。祝你好运!