A place for online solutions for 3D modeling of objects. In a short time, create the desired drawing or model in Catia V5.

4/28/2024

Find Unique Persons Using Python Function

 How to write a Python function to show the number of unique persons and their names from a given list of persons.

 


Here's a Python function to show the number of unique persons and their names from a given list of persons:

def unique_persons(persons):

    unique_names = set()  # Create an empty set to store unique names

    for person in persons:

        unique_names.add(person['name'])  # Add each person's name to the set

    num_unique_persons = len(unique_names)  # Get the number of unique names

    return num_unique_persons, unique_names


# Example list of persons

persons = [

    {'name': 'Alice', 'age': 30},

    {'name': 'Bob', 'age': 25},

    {'name': 'Alice', 'age': 35},

    {'name': 'Charlie', 'age': 40},

    {'name': 'Bob', 'age': 22}

]


# Call the function

num_unique, unique_names = unique_persons(persons)


# Print the results

print("Number of unique persons:", num_unique)

print("Unique names:", unique_names)

This function iterates through the list of persons and adds each person's name to a set, which automatically removes duplicates. Then, it returns the number of unique names and the set of unique names.

Inserted in the Jupyter IDE after calling the code looks like this: 

https://i.imgur.com/x998Sup.png

It can be seen that Alice and Bob are not reproduced, the names being duplicated

Of course, this is just a code example. Persons list can be extended to hundreds or thousands of people or instead of persons the list can contain objects with a certain value and a certain size.

No comments:

Post a Comment

any suggestion: