Hassan Baig Hassan Baig - 2 months ago 10
Python Question

Extracting a set from a list of composite elements in python

I'm maintaining

message_id
and
message_writer_id
together in a python list like so:

composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1', ...]


Where each element is
message_id:message_poster_id
.

From the above list, I want to extract the
set
of all
message_writer_ids
. I.e. I want to extract a
set
containing all unique numbers after
:
so that I end up with:

item_set = ['2', '1', '19']


What's the most efficient way to do that in python?




Currently, I'm thinking I'll do something like:

new_list = []
for item in composite_items:
element = item.split(":")[1]
new_list.append(element)
new_set = set(new_list)


Was wondering if there's a faster way to achieve this.

Answer
composite_items = ['1:2', '2:2', '3:2', '4:1', '5:19', '20:2', '45:1']

unique = set(i.split(":")[1] for i in composite_items)
Comments