数组的类型为String 。由于添加""需要耗费时间,因此我将其编写为Int。遗憾。
我有两个阵列说var array1 = [[1,2,3,4,5,6,7,8,9]]
和
var array2 = [[1,2,3,4],
[2,3,4,5],
[2,4,5,6],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8],
[2,3,4,5,6,7,8]]
我必须将array2
的每个数组元素与array1
进行比较,并插入' - '元素不匹配的地方。像这样,
var array2 = [[1,2,3,4,-,-,-,-,-],
[-,2,3,4,5,-,-,-,-],
[-,2,-,4,5,6,-,-,-],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,-],
[-,2,3,4,5,6,7,8,-]]
我试图遍历array2中的每个数组并将其与array1进行比较,比较索引并插入' - '到索引位置我,但我得到了意想不到的结果。
更新
for item in array2{
var elementsArray = item
for i in stride(from: 0, to: elementsArray.count, by: 1) {
if elementsArray[i] != array1[i]
{
elementsArray.insert("-", at: i)
}
print("elemnt array.....", elementsArray, "\n\n")
}
}
我曾想过将array1的每个数组与array1进行count
比较,找到不常见元素的索引,然后插入' - '在那个指数位置。这种方法对吗?请帮帮我。
答案 0 :(得分:2)
您需要一个新数组,其中array2
的每一行都被替换为array1
let array1 = [1,2,3,4,5,6,7,8,9]
let array2 = [[1,2,3,4],
[2,3,4,5],
[2,4,5,6],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8],
[2,3,4,5,6,7,8]]
let filled = array2.map { row in
array1.map {
row.contains($0) ? String($0) : "-"
}
}
for row in filled { print(row) }
,行中最初不存在的元素替换为“ - ”:
Set(row)
输出:
["1", "2", "3", "4", "-", "-", "-", "-", "-"] ["-", "2", "3", "4", "5", "-", "-", "-", "-"] ["-", "2", "-", "4", "5", "6", "-", "-", "-"] ["1", "2", "3", "4", "5", "6", "7", "8", "9"] ["1", "2", "3", "4", "5", "6", "7", "8", "-"] ["-", "2", "3", "4", "5", "6", "7", "8", "-"]
对于大型数组,可以通过创建elementsArray
来改进
更快的遏制检查,或利用这些元素
正在递增。
您的方法无效,因为static
迭代时修改它。