比较2个数组并列出差异-Swift [英] Compare 2 arrays and list the differences - Swift
问题描述
我想知道如何比较两个布尔数组并列出不匹配的布尔值.
I was wondering how one would go about comparing 2 boolean arrays and listing the non matching booleans.
我写了一个简单的2个数组的例子.
I have written up a simple example of 2 arrays.
let array1 = [true, false, true, false]
let array2 = [true, true, true, true]
我如何比较array1&并显示不匹配的数组.我正在尝试执行此操作以检查问答游戏的用户结果.
How would I compare array1 & array2 and display the non matching. I am trying to do this to check user results for a quiz game.
谢谢!
推荐答案
这里是一个实现,但是要说它到底是不是一个完全不可能,因为您尚未指定要执行的操作认为答案应该为:
Here's one implementation, but whether it is the one you are after is completely impossible to say, because you have not specified what you think the answer should be:
let answer = zip(array1, array2).map {$0.0 == $0.1}
这将为您提供布尔值的列表,如果答案与正确的答案匹配,则为true
,如果答案不正确,则为false
.
That gives you a list of Bool values, true
if the answer matches the right answer, false
if it does not.
但是,假设您想要的是正确答案的索引列表.然后您可以说:
But let's say what you wanted was a list of the indexes of those answers that are correct. Then you could say:
let answer = zip(array1, array2).enumerated().filter() {
$1.0 == $1.1
}.map{$0.0}
如果要列出不正确正确答案的索引列表,只需将==
更改为!=
.
If you want a list of the indexes of those answers that are not correct, just change ==
to !=
.
这篇关于比较2个数组并列出差异-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!