我试图用零填充一个数组,但是在swift中找不到简洁的方法。 如果我有数组x = [1,2,3; 4,5,6; 7,8,9] 在matlab中我可以使用命令
y = [zeros(1,3+2);zeros(3,1),x,zeros(3,1);zeros(1,3+2)]
给出[0,0,0,0,0; 0,1,2,3,0; 0,4,5,6,0; 0,7,8,9,0; 0,0,0,0,0]
然而到目前为止,在一个快速的游乐场中,我只能单独引用每个元素以正确形成新数组。
到目前为止我尝试过的方法是使用x作为输入,y作为输出,第一个类似于matlab,
var x = [[1,2,3,],[4,5,6],[7,8,9]]
var y = [[0,0,0,0,0],[0,x[0],0],[0,x[1],0],[0,x[2],0],[0,0,0,0,0]]
第二个是循环
for i in 0 ..< x.count + 1 {
if i == 0 || i == x.count - 1 {
y[i] = [0,0,0,0,0]
}
else{
y[i] = [0, x[i-1] ,0]
}
}
不是在Xcode游乐场预览中看起来像标准数组,而是给出的输出。
[[0, 0, 0, 0, 0], [0, […], 0], [0, 0, 0, 0, 0], [0, […], 0], [0, 0, 0, 0, 0]]
使用代码
也非常奇怪地打印到控制台for i in 0 ..< y.count {
print("\(y[i])")
}
输出
(
0,
0,
0,
0,
0
)
(
0,
(
1,
2,
3
),
0
)
(
0,
0,
0,
0,
0
)
(
0,
(
7,
8,
9
),
0
)
(
0,
0,
0,
0,
0
)
与预期的
相反[0, 0, 0, 0, 0]
[0, 1, 2, 3, 0]
[0, 4, 5, 6, 0]
[0, 7, 8, 9, 0]
[0, 0, 0, 0, 0]
这样做的最佳方式是什么?
答案 0 :(得分:2)
我制作了appzYourLife's answer的通用版本,它可以采用任意嵌套数组类型。它还增加了对顶部和底部填充的支持
extension Array where Element: _ArrayType {
typealias InnerElement = Element.Generator.Element
func pad2DArray(with padding: InnerElement,
top: Int = 0, left: Int = 0,
right: Int = 0, bottom: Int = 0) -> [[InnerElement]] {
let newHeight = self.count + top + bottom
let newWidth = (self.first?.count ?? 0) + left + right
var paddedArray = [[InnerElement]](count: newHeight, repeatedValue:
[InnerElement](count: newWidth, repeatedValue: padding))
for (rowIndex, row) in self.enumerate() {
for (columnIndex, element) in row.enumerate() {
paddedArray[rowIndex + top][columnIndex + left] = element
}
}
return paddedArray
}
}
var input = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
let result = input.pad2DArray(with: 0, top: 1, left: 1, right: 1, bottom: 1)
/*
result:
[
[0, 0, 0, 0, 0],
[0, 1, 2, 3, 0],
[0, 4, 5, 6, 0],
[0, 7, 8, 9, 0],
[0, 0, 0, 0, 0],
]
*/
答案 1 :(得分:0)
如果您定义此扩展程序
extension _ArrayType where Element == Int {
func pad(left left: Int, right: Int) -> [Int] {
let leftSide = [Int](count: left, repeatedValue: 0)
let rightSide = [Int](count: right, repeatedValue: 0)
return leftSide + (self as! [Int]) + rightSide
}
}
然后你可以写
[1,2,3].pad(left: 1, right: 1) // [0, 1, 2, 3, 0]
答案 2 :(得分:0)
绝对不如接受的答案那么优雅,但它仍然有效:
var x = [[1,2,3,],[4,5,6],[7,8,9]]
var y = [[Int]]()
y.insert([0,0,0,0,0], atIndex: 0)
for i in 0 ..< x.count {
var intArray: [Int] = []
for number in x[i] {
intArray.append(number)
}
intArray.insert(0, atIndex: 0)
intArray.insert(0, atIndex: intArray.count)
y.append(intArray)
}
y.insert([0,0,0,0,0], atIndex: x.count + 1)
的输出
for i in 0 ..< y.count {
print("\(y[i])")
}
是
[0,0,0,0,0]
[0,1,2,3,0]
[0,4,5,6,0]
[0,7,8,9,0]
[0,0,0,0,0]