概念化集合理解

Bra*_*ice 0 python dictionary set set-comprehension

def nfa_eclosure(M, s):
    """
    >>> M = [{'':{1,2,3}}, {'b':{1}}, {'a':{2}}]
    >>> nfa_eclosure(M, 0)
    set([0, 1, 2, 3])
    """
    try:
        states = {nfa_eclosure(M, x+1) for x in xrange(len(M[s])) if M[s].get('')}
    except IndexError:
        states = set([])
    states.add(s)
    return states
Run Code Online (Sandbox Code Playgroud)

运行此抛出,TypeError: unhashable type: 'set'但我看不到问题。


编辑:2014-02-03 15:25:00

谢谢大家的解释。那讲得通。有没有一种“ pythonic”的方式来获取我现在拥有的代码,然后将集合的内容“ splat”到新的集合中,而不是将所有内容都转换为frozenset,然后将其展平?


编辑:2014-02-04 00:41:00

我做了一些修改,现在我想到了:

try:
    return set([s]).union(*(nfa_eclosure(M, x) for x in M[s].get('')))
except IndexError:
    return set([s])
Run Code Online (Sandbox Code Playgroud)

但我有新的错误信息

TypeError: union() argument after * must be a sequence, not generator
Run Code Online (Sandbox Code Playgroud)

谷歌搜索并不能很好地解释这种情况。知道发生了什么事吗?

mhl*_*ter 5

您正在试图建立一个setsetS,递归。不允许这样做,因为sets是unhashable,因此不能放在set。您可以使用,frozenset因为它们是可哈希的。

try:
    states = frozenset({nfa_eclosure(M, x+1) for x in xrange(len(M[s])) if M[s].get('')})
except IndexError:
    states = frozenset([])
Run Code Online (Sandbox Code Playgroud)

sets是无序的,正是因为它们是由其成员的哈希在内部进行排序的。这样可以快速查找集合成员。

在文档上阅读有关集合和可哈希的信息