Home > Software design >  How do i group values into a list from a group of values with repeating values in python
How do i group values into a list from a group of values with repeating values in python

Time:01-26

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.

CodePudding user response:

Use a set comprehension, like this:

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

CodePudding user response:

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?

CodePudding user response:

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']
  • Related