I have a Counter()
object that gives me count occurrences of a list of strings. And I have a unique list of strings. And I need to yield a list of counts from the counter and then put zeros to the other string instances that have 0 counts.
I can do it as the following but can I achieve the same z
list in a more efficient/pythonic way?
from collections import Counter
x = Counter(['abc','def','abc'])
uniq = sorted(set(['abc', 'def', 'abc', 'abc', 'ghi', 'jkl','jkl']))
z = [x[i] for i in uniq]
Output
>>> z
[2, 1, 0, 0]
>>> uniq
['abc', 'def', 'ghi', 'jkl']
Actually the ultimate aim is to get an np.array(z)
and np.array(uniq)
I suppose you could use the Counter
's update
method to add 0 to all of the keys in the unique list
>>> from collections import Counter
>>> x = Counter(['abc','def','abc'])
>>> y = ['abc', 'def', 'abc', 'abc', 'ghi', 'jkl','jkl']
>>> x.update(dict.fromkeys(y, 0))
So that x
now contains the keys and values you want.
Or, if you want to avoid the construction of the intermediate dict
, the slightly longer:
>>> from collections import Counter
>>> x = Counter(['abc','def','abc'])
>>> y = ['abc', 'def', 'abc', 'abc', 'ghi', 'jkl','jkl']
>>> for k in y:
x[k] += 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.