Manatsa Mbanje
Manatsa Mbanje

Reputation: 31

How do i group values into a list from a group of values with repeating values in python

i have values derived from a block of code that extracts those values from aws s3. The code which extacts these values is this.

for my_bucket_files in bucket_name.objects.all():
    split_objects = my_bucket_files.key.split('/')
    single_split_objects = split_objects[0]
    print(single_split_objects)

This prints out a values in a format like this:

air squat 
air squat
air squat
air squat
push up
push up 
push up
push up
lunges 
lunges
lunges
bench press
bench press
bench press 

I wanna group these values such that i get a list of values that come back in a format whether be it a list as long as i can utilise it later on.

air squat
push up
lunges
bench press

How do i go about doing this.

Upvotes: 0

Views: 42

Answers (3)

Stuart
Stuart

Reputation: 9868

Use a set comprehension, like this:

unique_values = {b.key.split("/")[0] for b in bucket_name.objects.all()}

Upvotes: 2

Talha Tayyab
Talha Tayyab

Reputation: 27930

lst=[]
for my_bucket_files in bucket_name.objects.all():
    split_objects = my_bucket_files.key.split('/')
    single_split_objects = split_objects[0]
    if single_split_objects not in lst:
        lst.append(single_split_objects)
print(lst)
['air squat','push up','lunges','bench press']

Upvotes: 0

K. Shores
K. Shores

Reputation: 1005

If you mean that you want a unique list

collection = set()
for my_bucket_files in bucket_name.objects.all():
    split_objects = my_bucket_files.key.split('/')
    single_split_objects = split_objects[0]
    collection.add(single_split_objects)
uniq = list(collection)

collection is a set. Sets contain unique elements only so the add function will only add an element if it is not already contained within the set.

Because sets are iterable, list(collection) will convert the set to a list.

Is this what you're looking for?

Upvotes: 0

Related Questions