This question already has answers here:
Counting Letter Frequency in a String (Python) [duplicate]
(13 answers)
Closed 3 years ago.
I have a string l1 that for example contains the following content: aackcdldccc. I would like to count the number of times that each character occurs using dictionary. The required final result should be a dictionary like this:
a:2
c:5
k:1
d:2
l:1
How can I fix my code so it will work?
I use the following code and get error message:
l1= ('aackcdldccc')
print (l1)
d={}
print (len(l1))
for i in (range (len(l1))):
print (i)
print (l1[i])
print (list(d.keys()))
if l1[i] in list(d.keys()):
print ('Y')
print (l1[i])
print (list(d.keys())[l1[i]])
d1 = {l1[i]:list(d.values())[l1[i]+1]}
#print (d1)
#d.update (d1)
else:
print ('N')
d1={l1[i]:1}
d.update (d1)
Here is the error I get:
aackcdldccc
11
0
a
[]
N
1
a
['a']
Y
a
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-185-edf313da1f8d> in <module>()
10 print ('Y')
11 print (l1[i])
---> 12 print (list(d.keys())[l1[i]])
13 #d1 = {l1[i]:list(d.values())[l1[i]+1]}
14 #print (d1)
TypeError: list indices must be integers or slices, not str
There are two ways to do this:
In [94]: s = 'aackcdldccc'
In [95]: collections.Counter(s)
Out[95]: Counter({'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1})
In [96]: d = {}
In [97]: for char in s:
...: d.setdefault(char, 0)
...: d[char] += 1
...:
In [98]: d
Out[98]: {'a': 2, 'c': 5, 'k': 1, 'd': 2, 'l': 1}
Related
I have the following pandas dataframe
data = [{'a': 1, 'b': '[2,3,4,5,6' }, {'a': 10, 'b': '[54,3,40,5'}]
test = pd.DataFrame(data)
display(test)
a b
0 1 [2,3,4,5,6
1 10 [54,3,40,5
I want to list the number in column b, but as the list has the [ only at the beginning, doesnt allow me to create the list, I'm trying to remove the "[" so I can extract the numbers, but I keep getting errors, what I'm doing wrong?
This is how the numbers are stored
test.iloc[1,1]
'[54,3,40,5'
And this is what I've tried to remove the "[".
test.iloc[0,1].replace("[",'', regex=True).to_list()
test.iloc[0,1].str.replace("[\]\[]", "")
What i want to achieve is to have b as a proper list so i can apply other functions.
a b
0 1 [2,3,4,5,6]
1 10 [54,3,40,5]
To make your 'b' column a list you can first delete the open squared bracket at the beginning, and then use the split method on each element of your 'b' column
test['b'] = test['b'].str.replace('[', '').map(lambda x: x.split(','))
test
# a b
# 0 1 [2, 3, 4, 5, 6]
# 1 10 [54, 3, 40, 5]
try it:
def func(col):
return eval(col+']')
test['b'] = test['b'].apply(func)
import pandas as pd
data = [{'a': 1, 'b': '[2,3,4,5,6' }, {'a': 10, 'b': '[54,3,40,5'}]
test = pd.DataFrame(data)
print(test['b'][0][1:])
for i in range(len(test['b'])):
test['b'][i] = test['b'][i][1:]
I have such a nums list
In [72]: nums
Out[72]: [4, 1, 2, 1, 2]
try to get the unique number from the list
n [72]: nums
Out[72]: [4, 1, 2, 1, 2]
In [73]: c = Counter(nums)
In [74]: c
Out[74]: Counter({4: 1, 1: 2, 2: 2})
I can see the result from the counter, it is 4:1, but cannot retrieve it in O(1) time
In [79]: list(c)[0]
Out[79]: 4 #O(n) time
Is it possible to get 4 in O(1)time
According to the comments to the question, you want to get the elements that have a count of 1. But it is still not clear what you want to get exactly, as the term "the first element" is unclear in the context of a Counter, which is a dict and no defined order internally.
Here are a few options (I used str instead of int to make it clearer which are the values and which are their counts):
>>> import collections
>>> input_str = 'awlkjelqkdjlakd'
>>> c = collections.Counter(input_str)
>>> c
Counter({'l': 3, 'k': 3, 'a': 2, 'j': 2, 'd': 2, 'w': 1, 'e': 1, 'q': 1})
Get all elements that have count of 1 (takes O(k), where k is the number of different elements):
>>> [char for char, count in c.items() if count == 1]
['w', 'e', 'q']
Get one (random, not specified) element that has count of 1 (takes O(k), because the list has to be built):
>>> [char for char, count in c.items() if count == 1][0]
'w'
This can be improved by using a generator, so the full list will not be built; the generator will stop when the first element with count 1 is found, but there is no way to know if that will be first or last or in the middle ...
>>> g = (char for char, count in c.items() if count == 1)
>>> g
<generator object <genexpr> at 0x7fd520e82f68>
>>> next(g)
'w'
>>> next(char for char, count in c.items() if count == 1)
'w'
Now, if you want to find the count of the first element of your input data (in my example input_str), that is done in O(1) because it is a list item access and then a dict lookup:
>>> elem = input_str[0]
>>> elem
'a'
>>> c[elem]
2
But I cannot give a more concrete answer without more information on what exactly you need.
How can I iterate over only X number of dictionary items? I can do it using the following bulky way, but I am sure Python allows a more elegant way.
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
x = 0
for key in d:
if x == 3:
break
print key
x += 1
If you want a random sample of X values from a dictionary you can use random.sample on the dictionary's keys:
from random import sample
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
X = 3
for key in sample(d, X):
print key, d[key]
And get output for example:
e 5
c 3
b 2
This question already has answers here:
How do I count the occurrences of a list item?
(29 answers)
Closed 4 years ago.
I have 5 set of lists and some of strings in those lists are repetitive
now! I wanna know the number of repetition! for example the word "A" is in all of my lists by "B" is just in "3" or "C" is in 4 of them.
How can I sort this problem, by using remove() I faced to wrong answer
Thank you in advance!
Take a look at Counter
from collections import Counter
a = ['a','a','b','b']
b = ['b','b','c','d']
c = a+b
cnt = Counter()
for x in c:
cnt[x] +=1
print(cnt)
Counter({'a': 2, 'b': 4, 'c': 1, 'd': 1})
The above will get you counts of each but it seems like you're more concerned at a list level.
from collections import defaultdict
f = defaultdict(list)
a = ['a','a','b','b']
b = ['b','b','c','d']
c = ['e','f','g','h']
d = a + b + c
for i in d:
f[i] = 0
if i in b:
f[i] += 1
if i in c:
f[i] +=1
if i in a:
f[i] +=1
print (f)
defaultdict(list,
{'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1, 'h': 1})
This question already has answers here:
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
(22 answers)
Closed 5 years ago.
How to add the values of two dictionary ?
Ex :
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
result must be
c = {'a':11,'b':12,'c':21}
You can easily add two dictionaries by using Counter class of collections library for ex:
from collections import Counter
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
a = Counter(a)
b = Counter(b)
c = dict(a + b)
print c
OUTPUT
{'c': 21, 'b': 12, 'a': 11}
Next some please show some effort..
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
c = {k: a[k] + b[k] for k in a}
print(c) # {'c': 21, 'b': 12, 'a': 11}
The above works fine if we assume that a and b have the same keys.
If that is not the case, you can try the following:
a = {'a': 10, 'b': 11, 'c': 20, 'h': 5}
b = {'a': 1, 'b': 1, 'c': 1, 'd': 12}
all_keys = set(a.keys()) # in Python 3 it can be simplified as `all_keys = set(a)`
all_keys.update(b.keys()) # in Python 3 it can be simplified as `all_keys.update(b)`
c = {k: a.get(k, 0) + b.get(k, 0) for k in all_keys}
print(c) # {'c': 21, 'h': 5, 'a': 11, 'b': 12, 'd': 12}
Notice that i am using get on both dictionaries to skip the check on the existence of the key.