list 串列中,如何將Class Object重複值去除,,取unique值?
How to remove duplicate class object in List?
Example: 假設一個data class object 展開有 id, data, etc, …
data > id
> data
> etc.
> etc.
# There id is not equal/ or equal
data_list = [data, data, data, data, data, data]
我們將id做為主要的篩選值
We want to filter duplicate data object
in a list based on data.id
data_list = [data, data, data, data, data, data]
new_data_list = []
# 需要一個unique id的串列, 第一次迴圈會新增id
# 每次迴圈的data物件若id已在unique_id內, 就會pass
# make data unique id to filter data
unique_id = []
for data in data_list:
if data.id not in unique_id:
# if id is not in list, add id and data
# if id is in list, pass/ don't add data
unique_data_list.append(data.id)
# 若id 不在 list 內 才會新增
new_data_list.append(data)
每個物件中,id 是獨特的, 所以若有重複的data(id也會重複),就用這樣的方法去取出unique的data
算是在迴圈中陸續往前比對id有沒有重複,沒有重複才會新增data, 有重複就去除