Arrays 创建字典:将整数数组作为键分配给另一个数组
我有一个数组和一个整数数组,我想用整数数组元素作为数组元素的键来创建一个字典 我尝试了很多迭代方法,但运气不好。有什么想法或想法吗Arrays 创建字典:将整数数组作为键分配给另一个数组,arrays,swift,dictionary,Arrays,Swift,Dictionary,我有一个数组和一个整数数组,我想用整数数组元素作为数组元素的键来创建一个字典 我尝试了很多迭代方法,但运气不好。有什么想法或想法吗 var populationArray = [[98, 8, 45, 34, 56], [9, 13, 65, 4, 90], [24, 5, 4, 56, 88], [3, 55, 22, 19, 10], [8, 33, 26, 93, 16], [31, 38, 92, 70, 36], [9, 39, 15, 14, 66]] var IntegerKey
var populationArray = [[98, 8, 45, 34, 56], [9, 13, 65, 4, 90], [24, 5, 4, 56, 88], [3, 55, 22, 19, 10], [8, 33, 26, 93, 16], [31, 38, 92, 70, 36], [9, 39, 15, 14, 66]]
var IntegerKeys = [17, 41, 10, 34, 5, 85, 87]
var Dictionary : [Int: [Int]] = [:]
试试这个:
var populationArray = [[98, 8, 45, 34, 56], [9, 13, 65, 4, 90], [24, 5, 4, 56, 88], [3, 55, 22, 19, 10], [8, 33, 26, 93, 16], [31, 38, 92, 70, 36], [9, 39, 15, 14, 66]]
var IntegerKeys = [17, 41, 10, 34, 5, 85, 87]
var Dictionary = [Int: [Int]]()
// Swift 2.0
for (index, key) in IntegerKeys.enumerate() {
Dictionary[key] = populationArray[index]
}
// Swift 1.2
for (index, key) in enumerate(IntegerKeys) {
Dictionary[key] = populationArray[index]
}
试试这个:
var populationArray = [[98, 8, 45, 34, 56], [9, 13, 65, 4, 90], [24, 5, 4, 56, 88], [3, 55, 22, 19, 10], [8, 33, 26, 93, 16], [31, 38, 92, 70, 36], [9, 39, 15, 14, 66]]
var IntegerKeys = [17, 41, 10, 34, 5, 85, 87]
var Dictionary = [Int: [Int]]()
// Swift 2.0
for (index, key) in IntegerKeys.enumerate() {
Dictionary[key] = populationArray[index]
}
// Swift 1.2
for (index, key) in enumerate(IntegerKeys) {
Dictionary[key] = populationArray[index]
}
@ZoffDino的答案确实有效,但是如果
populationArray
包含的元素少于integerKeys
,它就会崩溃。我提出的方法没有这个缺陷:
var populationArray = [[98, 8, 45, 34, 56], [9, 13, 65, 4, 90], [24, 5, 4, 56, 88], [3, 55, 22, 19, 10], [8, 33, 26, 93, 16], [31, 38, 92, 70, 36], [9, 39, 15, 14, 66]]
var IntegerKeys = [17, 41, 10, 34, 5, 85, 87]
var dictionary : [Int: [Int]] = [:]
for (key, value) in zip(IntegerKeys, populationArray) {
dictionary[key] = value
}
@ZoffDino的答案确实有效,但是如果
populationArray
包含的元素少于integerKeys
,它就会崩溃。我提出的方法没有这个缺陷:
var populationArray = [[98, 8, 45, 34, 56], [9, 13, 65, 4, 90], [24, 5, 4, 56, 88], [3, 55, 22, 19, 10], [8, 33, 26, 93, 16], [31, 38, 92, 70, 36], [9, 39, 15, 14, 66]]
var IntegerKeys = [17, 41, 10, 34, 5, 85, 87]
var dictionary : [Int: [Int]] = [:]
for (key, value) in zip(IntegerKeys, populationArray) {
dictionary[key] = value
}
甜蜜的。;)谢谢@zoff dinoSweet.)谢谢@zoff dinoSweet。我完全没有意识到这一点。谢谢好极了。我完全没有意识到这一点。谢谢