Skip to main content
 首页 » 编程设计

python之构建列表列表的字典理解 : referencing the current value for a key during comprehension

2025年05月04日13zhoujg

我正在尝试创建一个基于哈希的列表列表。也就是说,我想要一个散列相同的项目列表列表。这在单行理解中可能吗?

这是无需理解即可运行的简单代码:

def list_of_lists(items): 
    items_by_hash = defaultdict(list) 
    for item in items: 
        words_by_key[hash(item)].append(item) 
    return words_by_key.values() 

例如,假设我们有这个简单的哈希函数:

def hash(string): 
    import __builtin__ 
    return __builtin__.hash(string) % 10 

然后,

>>> l = ['sam', 'nick', 'nathan', 'mike'] 
>>> [hash(x) for x in l] 
[4, 3, 2, 2] 
>>> 
>>> list_of_lists(l) 
[['nathan', 'mike'], ['nick'], ['sam']]  

有什么办法可以理解吗?我需要能够引用我正在构建的字典,以便将下一个项目附加到列表值。

这是我得到的最好的,但它不起作用:

>>> { hash(word) : [word] for word in l }.values() 
[['mike'], ['nick'], ['sam']] 

它显然每次都创建一个新列表,这不是我想要的。我想要类似的东西

{ hash(word) : __this__[hash(word)] + [word] for word in l }.values() 

或

>>> dict([ (hash(word), word) for word in l ]) 
{2: 'mike', 3: 'nick', 4: 'sam'} 

但这会导致同样的问题。

请您参考如下方法:

[[y[1] for y in x[1]] for x in itertools.groupby(sorted((hash(y), y) 
  for y in items), operator.itemgetter(0))]