我有以下两个数组:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
我想将它们合并到一个如下所示的数组中:
[ ("monday", 1), ("tuesday", 2), ("wednesday", 3), ("thursday", 4), ("friday", 5)]
答案 0 :(得分:10)
使用zip
和map
:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
let tuples = zip(xaxis, yaxis).map { ($0, $1) }
答案 1 :(得分:3)
试试这个:
let xaxis = ["monday", "tuesday", "wednesday", "thursday", "friday"]
let yaxis = [1, 2, 3, 4, 5]
var newArr = [(String, Int)]()
for i in 0..<xaxis.count {
newArr.append((xaxis[i], yaxis[i]))
}
print(newArr)
答案 2 :(得分:2)
试试这个:
let arrayMerged = zip(xaxis, yaxis).map { ($0, $1) }
或者这个:
let arrayMerged = Array(zip(xaxis, yaxis))
答案 3 :(得分:1)
let tuples = xaxis.enumerated().map { (index, value) in (value, yaxis[index]) }
假设yaxis
的计数始终与xaxis
匹配。