【问题标题】:How to flag end of loop over dictionary with two int's tuple as key - combination-like loop needed如何用两个int的元组作为键在字典上标记循环结束 - 需要类似组合的循环
【发布时间】:2013-04-30 12:34:16
【问题描述】:

我在内存中有一本具有以下模式的字典:

value_refs[tuple([a,b])] = some float value

字典是 4000 个参考值的所有可能组合的集合,之前计算过(数百万个)。 例如:

...
value_refs[1,4] =0,76543
value_refs[1,5] =0,89734 #i want this value, since it is the bigger of all the second ref's,
                         # related with the ref. 1 (first tuple in the key)
...
value_refs[1,4000] =0,77543
...
...
value_refs[4000,30] =0,76543
value_refs[4000,31] =1,89734 # I want this value, since it is the bigger of all the second
                             # references, related with the ref. 4000 (first tuple in the key)
value_refs[4000,32] =0,77543

问题是我不知道如何以与“组合”相同的模式对整个字典键进行循环,将它们用作可迭代对象,例如:

asymptote=0
cache=[]
pool_chain={}

for c in value_refs.keys()[c][0]: # [0] because i need the first tuple value of the key, by rank
    for d in value_refs.keys()[d][1]: # [1] because i need a loop over the range of all the second
                                    #tuple values in the dict pool, versus the outer loop
        while True:
            try:
                if value_refs[c,d] > asymptote:
                    cache=[c,d]
                    asymptote=value_refs[c,d]
            except KeyError:
                pass
            except StopIteration:
                pool_chain[cache]=asymptote
                asymptote=0
        #and now c would advance by an ordered rank intil the number 4000...

我知道上面的代码不起作用,因为语法不好,但我认为这是发布问题的最佳方式。 python中字典的无序性质是(我认为)嵌套循环以有序方式处理2元组键的问题,如1,2,1,3 ... 1,4000 2,3 2,4等等。我如何以有序的方式(按等级)遍历内存中的字典并提取 2 元组键和键中第二个值与同一键中的第一个元组值最大的值,这适用于所有组合?提前致谢。

【问题讨论】:

  • 我认为如果您将value_refs 重新设计为dict of dicts,您的生活会轻松很多。这样您就可以轻松引用value_refs[first_key] 或遍历第一个键。

标签: python loops dictionary


【解决方案1】:

具有 4000*4000 个元素的二维数组怎么样?占用更少的内存并且比这样的字典更快。特别是,如果您有所有可能的组合

看看Numpy

import numpy as np

arr = np.empty((4000,4000))
for i, a in enumerate([...]):
    for j, b in enumerate([...]):
        arr[i, j] = ...

...

for i in arr.shape[0]:
    for j in arr.shape[1]:
        ... arr[i, j]

【讨论】:

    【解决方案2】:

    我认为您想要做的是收集每个唯一密钥对的第一个值的最大值。

    这是一种方法:

    from collections import defaultdict
    
    all_values = defaultdict(list)
    
    keys = value_refs.keys()
    
    for k in keys:
       all_values[k[0]].append(value_ref[k])
    
    for k,v in all_values.iteritems():
       print i,max(v)
    

    【讨论】:

    • 是否可以跟踪“keys”变量中对应的第二个元组到各自的最大值?谢谢?
    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2023-01-25
    相关资源
    最近更新 更多