将由键值对字符串表示的图形转换为字典。Python

2024-04-26 11:22:56 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个地图,由一个由逗号分隔的两位数数字串表示,例如“12,23,34,45,56,67,78,81”,其中每对数字代表两个数字之间的路径,将字符串转换为字典表示的图形,其中键作为原点(数字),值作为键的可用目的地。e、 g 1:[2,8],2[3]等。 这是我丑陋的尝试:

def path(way):
x = way.split(',')
y = sorted(set(tele.replace(',','')))
graph = dict()
for i in x:
    for j in range(len(i)):
        for h in y:
            if h in i and i[j] != h:
                if h in graph:
                    graph[h].append((i[j]))
                else:
                    graph[h] = [(i[j])]
return graph

我打算在这之后实现广度优先搜索算法,以便找到最佳路径。如果我的解释不清楚,我很抱歉。任何帮助都将不胜感激,谢谢!在


Tags: 字符串in路径图形forif字典地图
1条回答
网友
1楼 · 发布于 2024-04-26 11:22:56
# this initializes values in the dictionary d with empty lists
# so that we can directly call .append() without checking "if key in keys"
from collections import defaultdict
d = defaultdict(list)

# your input string
s = "12,23,34,45,56,67,78,81"

# iterate through digit pairs
for pair in s.split(","):
  # get single digits from a pair
  fr = pair[0]
  to = pair[1]

  # add edges in both directions (undirected)
  d[fr].append(to)
  d[to].append(fr)

# see what we got
print d

结果

^{pr2}$

相关问题 更多 >