A very naive question.. I have the following function:
def vectorize(pos, neg):
vec = {item_id:1 for item_id in pos}
for item_id in neg:
vec[item_id] = 0
return vec
>>> print vectorize([1, 2] [3, 200, 201, 202])
{1: 1, 2: 1, 3: 0, 200: 0, 201: 0, 202: 0}
I feel, this is too verbose in python.. Is there a more pythonic way to do this... Basically, I am returning a dictionary whose values are 1 if its in pos (list) and 0 otherwise?
I'm not particularly sure if this is more pythonic... Maybe a little bit more efficient? Dunno, really
pos = [1, 2, 3, 4]
neg = [5, 6, 7, 8]
def vectorize(pos, neg):
vec = dict.fromkeys(pos, 1)
vec.update(dict.fromkeys(neg, 0))
return vec
print vectorize(pos, neg)
Outputs:
{1: 1, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0}
But I like your way too... Just giving an idea here.
I'd probably just do:
def vectorize(pos, neg):
vec = {}
vec.update((item, 1) for item in pos)
vec.update((item, 0) for item in neg)
return vec
But your code is fine as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With