你的代码工作得很好:
>>> from collections import defaultdict
>>> def next(s):
... x = defaultdict(set)
... for i in range(len(s)-1):
... x[i].add(s[i+1])
... return x
...
>>> next('hello')
defaultdict(<type 'set'>, {0: set(['e']), 1: set(['l']), 2: set(['l']), 3: set(['o'])})
也许您的运行代码defaultdict(str)
是偶然使用的?
不过,您想s[i]
用作键:
def next(s):
x = defaultdict(set)
for i in range(len(s)-1):
x[s[i]].add(s[i+1])
return x
这会产生所需的输出:
>>> def next(s):
... x = defaultdict(set)
... for i in range(len(s)-1):
... x[s[i]].add(s[i+1])
... return x
...
>>> next('hello')
defaultdict(<type 'set'>, {'h': set(['e']), 'e': set(['l']), 'l': set(['l', 'o'])})
您还可以将字符串作为迭代器循环,“记住”前一个字符:
def next_dict(s):
x = defaultdict(set)
prev = s[0]
for char in s[1:]:
x[prev].add(char)
prev = char
return x
跟踪先前的值,向后看比向前看要容易得多;毕竟,您已经传递了以前的值。