List filter, finding and counting duplicates

Posted under » Python » Django on 8 August 2024

From Python list »

In Django, assuming you have an associative array and want just the model id (m_id field) sorted by car type.

 model_list = []
 for mod in carass:
     model_list.append(mod.m_id)
 # use the model_list array
 carmod = cars.objects.filter(model__in=model_list).order_by('type')

Note that carass and cars are 2 separate tables or objects. The '__in' means the model is equal to the ids on the model_list array.

Somehow searching in arrays is quite forgiving. In the above example, it is a string, but it doesn't matter if it's a number (integer) or string.

def takenqid(request):
    global le
    id = request.user.id
    fresh = [518, 519, 520, 521, 523, 524]
    checkobj = Users.objects.filter(user_id=id)
    taken=[]
    for gay in checkobj:
        taken.append(gay.question_id)
    available = []
    for element in fresh:
        if element not in taken:
            available.append(element)
    le = available[0]
    return le

What the above Django function does is to see if there are anything from the fresh array that is not already in taken array. If there is then append to the available array. Useful when you want to give people content that the person has not seen.

Another way to look at it in Python using filter instead of appending to `available' list.

def takenqid(request):
    taken = [520, 521]
    if (request not in taken):
        return True
    else:
        return False
fresh = [518, 519, 520, 521, 523, 524]
available = filter(takenqid, fresh)
print('The available qid are:')
for le in available:
    print(le)

There are many ways to get unique records. or remove duplicates in Python. One way is to convert the list into dictionary which only accept unique data.

query ....

sid=[]
for pet in query:
    sid.append(pet.student_id)

unique_list = list(dict.fromkeys(sid))

for pet in unique_list:
    print(pet)

If you need to count the duplicates, by converting it to a dictionary

duplicates = ["a", "b", "a", "c", "c", "a", "c"]

my_dict = {i:duplicates.count(i) for i in duplicates}

print(my_dict)

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data