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

标签 python

给定一个 map ,由一串用逗号分隔的双位数数字表示,例如“12,23,34,45,56,67,78,81”,其中每对数字代表两个数字之间的路径,转换将字符串转换为由字典表示的图表,其中键作为起点(数字),值作为键的可用目的地。例如 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

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

最佳答案

# 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

结果

{'1': ['2', '8'], '3': ['2', '4'], '2': ['1', '3'], '5': ['4', '6'], '4': ['3', '5'], '7': ['6', '8'], '6': ['5', '7'], '8': ['7', '1']}

关于python - 将由键值对字符串表示的图转换为字典。 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475963/

相关文章:

python - 修改python中的函数而不调用它

python - 如何裁剪 numpy 数组的零边?

python - 如何在不锁定 Vim 的情况下运行当前的 python 脚本?

Python 生成器 : understanding the order of execution

python - 线程化快速创建大量图表

python - 在指定时间执行函数

python - BeautifulSoup:如何获得 div 选项卡的子项

python - 数字输出有时有.0

python - 如何使用 Django 和 Python 检查经过身份验证的用户的权限

python - Onesignal - 如何使用 python 向 Android 设备发送推送通知?