我正试图分析一组卡车及其携带物品的数据库,以找出哪两辆卡车最相似(即共享最多物品的卡车)。 我有一个类似于这样的CSV文件:
truck_id | item_id
13 | 85394 *
16 | 294 *
13 | 294 *
89 | 3115
89 | 85394
13 | 294
16 | 85394 *
13 | 3115
在上面的例子中,
16
和13
是最相似的货车,因为它们都有 294
和 85394
两个属性。整个代码太长,所以我提供伪代码来解释我的操作:
truck_items = {}
#1
loop over the csv:
add to truck_items a truck_id and an ARRAY with the items each truck has
#2
go over each truck in the truck_items dictionary, and compare their array to all other arrays
to get the count of similar items
#3
create a 'most_similar' key in the dictionary.
#4
check in most_similar what are the two trucks with most similarity.
那么最终我会得到像这样的东西:
{
13: [16, 2] // truck_1_id: [truck_2_id, number_similar_items]
89: ...
}
我知道这不是最有效的方法,因为我会多次遍历列表,这样做并不好。是否有更有效的方法?
truck_1_data['items']
,您会得到物品信息。同样的方式适用于truck_2_data['items']
。 - DeepSpace&
运算符可以返回它们的交集。 - DeepSpace