在对象数组中查找最近的项目?

时间:2018-04-09 08:34:06

标签: arrays swift filter

当我有一个数组中的项目的引用时,我想找到一个与它最接近的符合特定条件的项目。

例如,我有这个数组:

struct Person {
    var name = ""
    var age = ""
    var gender = ""
    var address = ""
}

let array = [Person(name:"ahmad",age:"22",gender:"male",address:"USA"),
             Person(name:"ahmad",age:"23",gender:"male",address:"KSA")]

现在让我说我有一个对象:

let object = Person(name:"ahmad",age:"25",gender:"male",address:"USA")

基于此,我需要根据其所有属性的值在array找到最接近它的人。

例如,根据我的上述代码,arrayobject中最接近的对象是第一个,因为它们具有相同的namegender和{ {1}}(3个匹配的属性),而不是第二个属性,因为只有2个匹配的属性。

1 个答案:

答案 0 :(得分:4)

首先,您必须定义一个测量“接近度”的函数 两个人根据您的示例

import xlwings as xw

filepath = ('file.xlsx')
wb = xw.Workbook(filepath)

sh = 'Sheet1'
l = [8,7,6,5,4,3,2,1]

for i in range(len(l)):
    xw.Range(sh , (3,2),(10,2)).value = l[i]

然后可以使用struct Person { let name: String let age: String let gender: String let address: String // Compute a number measuring the “closeness” to another person, // with smaller numbers meaning “closer”. // For example: the number of non-matching properties. func distance(to other: Person) -> Int { return (name == other.name ? 0 : 1) + (age == other.age ? 0 : 1) + (gender == other.gender ? 0 : 1) + (address == other.address ? 0 : 1) } } 确定最亲近的人:

min(by:)

上述距离法只是一个例子,你必须调整它 满足您的确切需求。