python - 如何在 Swift 中实现这个 Python 代码?
问题描述
如何在哈希表中实现哈希表?该示例是用 Python 编写的,我需要用 Swift 编写。
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
解决方案
首先你应该做的是正确定义的类型graph
,因为不像Python
你必须Swift
在声明中指定类型:
var graph: [String: [String: Int]] // Dictionary(hash table) with keys of type String and values of type Dictionary<String, Int>
然后你应该graph
用一些初始值进行初始化,因为Swift
你总是显式地初始化不可为空的变量:
graph = [:] // empty dictionary, in Python it's {}
声明和初始化可以在一行中,所以你可以这样做:
var graph: [String: [String: Int]] = [:]
然后是您的代码片段,几乎没有变化:
graph["start"] = [:]
graph["start"]?["a"] = 6 // ? can be replaced with ! here, because we know for sure "start" exists
graph["start"]?["b"] = 2 // but for simple tutorial purposes, I chose to use ? here
"start"
但是,如果您立即定义值会更好:
graph["start"] = [
"a": 6,
"b": 2
]
甚至可以整体做graph
:
let graph: [String: [String: Int]] = [
"start": [
"a": 6,
"b": 2
]
]
推荐阅读
- ssis - 如何在 SSIS 中的源/目标之间同步数据插入-更新-删除
- node.js - 如何在 forEach 循环节点中使用 Promise?
- java - 使用 AWS SDK for Java 2.x 将大文件上传到 S3 时内存不足
- python - 如何正确使用可选的 argparse 参数和子解析器
- c# - Linq 查询 - 根据条件跳过下一个查询执行
- php - exec:“php-fpm”:在 $PATH 中找不到可执行文件:未知
- c - C语言中的**是什么?
- python - 如何在 Jupyter Notebook 的一个单元格中显示两张图片?(matplotlib) (python)
- python - 从文本(日志)文件中的字典中检索值
- powerbi - DAX 与前一行进行比较并根据条件更新上游行