alist = ['A','B,'C','D']
此列表表示的是:A< - > B<> C< - > D
我希望将其映射如下:
答:B
B:A,C
C:B,D
D:C
起初我做了:
但这显然是错误的,因为它会跳过两个元素。
alist = ['A','B', 'C', 'D']
graph = {}
i = 2
while i < len(alist):
current, front, back = alist[i-1], alist[i-2], alist[i]
if current not in graph:
graph[current] = [front, back]
else:
graph[current].append(front)
graph[current].append(back)
i+=1
我该如何解决这个问题?
答案 0 :(得分:2)
如下:
graph = {}
for i, item in enumerate(alist):
connections = []
for j in (i-1, i+1): # look at element before and after the i'th
if 0 <= j < len(alist): # check if the index is valid for `alist`
connections.append(alist[j])
graph[item] = connections
请注意,这仅适用于alist
是某种序列。它不适用于发电机。另外,我通常不会检查列表中是否有索引。我宁愿try: ... except IndexError: ...
(EAFP),但IndexError
不会因为负j
而被提出,所以我避免了这个特定应用的路线。
答案 1 :(得分:2)
已经有很多解决方案,这个很容易理解:
alist = ['A','B', 'C', 'D']
graph = {}
for index, item in enumerate(alist):
if index == 0:
if len(alist) == 1:
graph[item] = []
break
graph[item] = [alist[index+1]]
elif index == len(alist)-1:
graph[item] = [alist[index-1]]
else:
graph[item] = [alist[index-1], alist[index+1]]
输出:
>>> print graph
154: {'A': ['B'], 'B': ['A', 'C'], 'C': ['B', 'D'], 'D': ['C']}
感谢@mglison在len(alist) == 1
编辑
答案 2 :(得分:0)
这几乎绝对不是你想要的,但对于你无法抗拒的问题,这是一个可爱的一线解决方案。
> l = ['A','B','C','D']
> { k: filter(None, [v1,v2]) for (k,v1,v2) in zip(l,[None]+l[:-1],l[1:]+[None]) }
{'A': ['B'], 'C': ['B', 'D'], 'B': ['A', 'C'], 'D': ['C']}
答案 3 :(得分:0)
这是一个快速而肮脏的解决方案(对于更长的项目,我有更好的方法)。
graph = {alist[0]: alist[1], alist[-1]: alist[-2]} # terminal elements
for i in range(1, len(alist)-1): # middle elements
graph[alist[i]] = [alist[i-1], alist[i+1]]
In [43]: for k, v in sorted(graph.iteritems()):
print "{} -> {}".format(k, v)
....:
A -> B
B -> ['A', 'C']
C -> ['B', 'D']
D -> C