gpt4 book ai didi

arrays - 数组到字典(无循环)

转载 作者:搜寻专家 更新时间:2023-11-01 07:05:02 24 4
gpt4 key购买 nike

假设,我有这样的数组:

var array = ["zero","one","two", "three"]

我想将它转换为 Dictionary,但键作为数组元素的索引,值是它自己喜欢的元素:

var dic = [0:"zero", 1:"one", 2:"two", 3:"three"]

最佳答案

您可以使用 Dictionary.uniqueKeysWithValueszip 的组合:

var array = ["zero","one","two", "three"]
var dict = Dictionary(uniqueKeysWithValues: zip(array.indices, array))
print(dict) // [0:"zero", 1:"one", 2:"two", 3:"three"]

关于arrays - 数组到字典(无循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48576627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com