swift中的zip函数
let words = ["one", "two", "three", "four"]
let numbers = 1...4
for (word, number) in zip(words, numbers) {
print("\(word): \(number)")
}
// Prints "one: 1"
// Prints "two: 2
// Prints "three: 3"
// Prints "four: 4"
但如果我想将[(one,1),(two,2),(three,3),(four,4)]
转置为["one", "two", "three", "four"]
和[1,2,3,4]
。
如何在swift中执行此操作,在Python中是否有类似的直接转换方法?
答案 0 :(得分:1)
您可以运行map
两次以“解压缩”数组:
let arr = [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
let arr1 = arr.map { $0.0 }
let arr2 = arr.map { $0.1 }
print(arr1) // ["one", "two", "three", "four"]
print(arr2) // [1, 2, 3, 4]
您也可以一次性使用reduce
执行此操作:
let (arr3, arr4) = arr.reduce(([], [])) { ($0.0 + [$1.0], $0.1 + [$1.1]) }
print(arr3) // ["one", "two", "three", "four"]
print(arr4) // [1, 2, 3, 4]