Loop through list until value is found then breaking? - python

I have a list: [1,2,3,4,5,6,0,9,2] that I want to loop through.
I want to create another list of dictionaries for every 3 elements until I reach a 0 element (i.e. the first dictionary will be {'gold':1,'silver':2,'bronze':3} and similarly for 4,5,6). The loop will terminate since it reaches 0.
So the resulting list would be: [{'gold':1,'silver':2,'bronze':3},{'gold':4,'silver':5,'bronze':6}]
Being new to Python and coming from a PHP background, how would I solve this leveraging functions like zip or map or would I have to resort to plain while loops?

from itertools import cycle
placings = cycle(['gold', 'silver', 'bronze'])
numbers = [1,2,3,4,5,6,0,9,2]
def zipper(numbers, placings):
d = {}
for n, c in zip(numbers, placings):
if n == 0:
break
d[n] = c
if n % 3 == 0:
yield d
d = {}
print list(zipper(numbers, placings))

from itertools import takewhile, islice
def groups(l, keys, i, n):
# lambda x: x != 0 -> take elements until we encounter any 0
tk = takewhile(lambda x: x != i, l)
while True:
d = dict(zip(keys, islice(tk, n)))
if len(d) == n: # make sure we have n keys in the dict
yield d
else:
break
keys = ['gold', 'silver', 'bronze']
print(list(groups(l,keys,0,3)))
[{'bronze': 3, 'gold': 1, 'silver': 2}, {'bronze': 6, 'gold': 4, 'silver': 5}]
takewhile
Make an iterator that returns elements from the iterable as long as the predicate is true.
So we only take elements up to the first i we encounter, d = islice(tk,n) takes a n length slice from our takewhile object using islice, we then create a dict from the passed in keys, Creating the dict consumes n elements at a time so we move to the next three elements each time we call it. If the length of the takewhile object is not a multiple of of n then we will have a dict at the end that is less than the size of n so if len(d) == n: will catch that and break the loop so the odd the length dict or an empty dict will terminate the while.
If you allow dicts with less than three keys:
from itertools import takewhile, islice,chain
def groups(l, keys, i, n):
tk = takewhile(lambda x: x != i, l)
return (dict(zip(keys, chain(islice(tk, n - 1),(i,)))) for i in tk)
Output:
In [5]: l = [1, 2, 3, 4, 5, 6, 7, 11, 6, 9, 0, 2]
In [6]: list(groups(l,['gold', 'silver', 'bronze'],0,3))
Out[6]:
[{'bronze': 1, 'gold': 2, 'silver': 3},
{'bronze': 4, 'gold': 5, 'silver': 6},
{'bronze': 7, 'gold': 11, 'silver': 6},
{'gold': 9}]
islice(tk, n - 1) takes a slice from our takewhile object len n - 1, we chain that and i so we get n elements each time.
Or use filter to filter out the dict with less than 3 keys:
def groups(l, keys, i, n):
tk = takewhile(lambda x: x != i, l)
return filter(lambda x: len(x) == n, (dict(zip(keys, chain(islice(tk, n - 1),(i,))))
for i in tk))
Which removes the shorter dict:
In [8]: list(groups(l,['gold', 'silver', 'bronze'],0,3))
Out[8]:
[{'bronze': 1, 'gold': 2, 'silver': 3},
{'bronze': 4, 'gold': 5, 'silver': 6},
{'bronze': 7, 'gold': 11, 'silver': 6}]
This does the same as the previous we just filter any potential odd length dict from the end. For python2 use itertools.ifilter instead of filter.

Easy! With a simple function, a data structure and simple iteration:
Example:
from collections import defaultdict
def f(xs, labels=("gold", "silver", "bronze")):
d = defaultdict(int)
n = 0
for i, x in enumerate(xs):
if x == 0: # break if we see a 0
return d
d[labels[n]] += i # update our counts
# cycle through gold/silver/bronze (labels)
n += 1
if n % 3 == 0:
n = 0
return d
xs = [1, 2, 3, 4, 5, 6, 0, 9, 2]
d = f(xs)
print d
Output:
$ python foo.py
defaultdict(<type 'int'>, {'bronze': 7, 'silver': 5, 'gold': 3})

First of all you need to break the larger list into smaller lists of same size as of list medals, to make the zip() function work correctly, Also the position of 0 in the list should be at a position divisible by the length of the medals list, Otherwise the last list among the smaller lists would have lesser number of elements.
listOfDictionary = []
lst = [1,2,3,4,5,6,0,9,2]
ind = lst.index(0) #Tells where to break the iteration loop.
medals = ["gold", "silver", "bronze"]
if ind%3==0:
newlst = [lst[i: i+3]for i in xrange(0,ind,3)]
#newlst = [[1, 2, 3], [4, 5, 6]]
for lsst in newlst:
listOfDictionary.append(dict(zip(medals, lsst)))
print listOfDictionary
>>> [{'bronze': 3, 'silver': 2, 'gold': 1}, {'bronze': 6, 'silver': 5, 'gold': 4}]

Using list comprehension in case of list and then using cycle
In [61]: mykeys
Out[61]: [1, 2, 3, 4, 5, 6, 0, 9, 2]
In [63]: mykeys1=[i for i in mykeys[:-1 if 0 not in mykeys else mykeys.index(0)]]
In [64]: myvalues
Out[64]: ['gold', 'silver', 'bronze']
In [66]: myvalues1=cycle(myvalues)
In [67]: mydict=dict(zip(mykeys1,myvalues1))
In [68]: mydict
Out[68]: {1: 'gold', 2: 'silver', 3: 'bronze', 4: 'gold', 5: 'silver', 6: 'bronze'}
In [69]: [dict(mydict.items()[i:i+3]) for i in range(0,len(mykeys1),3)]
Out[69]: [{1: 'gold', 2: 'silver', 3: 'bronze'}, {4: 'gold', 5: 'silver', 6: 'bronze'}]

Related

Finding only pairs in list using list comprehension

Looking for a fancy one line solution to finding pairs of items in a list using list comprehension.
I've got some code that finds multiples, but can't figure out how to split those multiples into pairs.
lst = [1,2,4,2,2,3,3,1,1,1,2,4,3,4,1]
len(set([x for x in lst if lst.count(x) > 1]))
Code above returns 4. Answer should be 6 pairs, [1,1,1,1,1] = 2, [2,2,2,2] = 2, [3,3,3] = 1 and [4,4,4] = 1.
Another approach would be using [Python 3.Docs]: class collections.Counter([iterable-or-mapping]):
>>> from collections import Counter
>>>
>>> lst = [1, 2, 4, 2, 2, 3, 3, 1, 1, 1, 2, 4, 3, 4, 1]
>>>
>>> c = Counter(lst)
>>> c
Counter({1: 5, 2: 4, 4: 3, 3: 3})
>>>
>>> sum(item // 2 for item in c.values())
6
and the one line equivalent:
>>> sum(item // 2 for item in Counter(lst).values())
6
A one-liner with no other intermediate variables would be:
sum(lst.count(x)//2 for x in set(lst))
It loops over set(lst) which contains all the distinct numbers in lst, and adds their pair counts.
You can do the following (if I've understood your pairing method properly):
lst = [1,2,4,2,2,3,3,1,1,1,2,4,3,4,1]
the_dict = {x: int((lst.count(x)/2)) for x in lst}
print(sum(the_dict.values()))
> 6
print(the_dict)
> {1: 2, 2: 2, 4: 1, 3: 1}
This makes a dictionary with the count of all pairs, then you can sum the values in the dictionary to get the pair count. Then you also have the dictionary available with the pair count of each value, if you need it.

set operation on a list of elements

I have a list containing thousands of sets similar to this:
set_list = [a, b, c, d]
each set in the list look something like this:
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 7, 9])
c = set([1, 2, 6, 8, 10, 12, 45])
d = set([11, 3, 23, 3, 4, 44])
I would like to do the set operation: X-(YUZUAUB......etc) for every set in the list, for example, this would look something like this:
after applying this operation on all elements in set_list the new elements look like this:
a = a.difference(b.union(c, d))
b = b.difference(c.union(a, d))
c = c.difference(d.union(b, a))
d = d.difference(a.union(c, b))
how do i accomplish this?
One possibility is to make use of the multiset module to precompute the multiset union of all elements in set_list, like so:
from multiset import Multiset
union = sum(set_list, Multiset())
set_list = [s - (union - s) for s in set_list]
Here, union - s computes the Y ∪ Z ∪ A ∪ B... in your notation.
See Aran-Fey's answer for the same method implemented (more verbosely) using only the standard library.
If I'm understanding correctly, you want the difference for each set and the union of the rest of the sets. I would use a loop and functools.reduce and operator.or_:
Setup
import functools
import operator
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 7, 9])
c = set([1, 2, 6, 8, 10, 12, 45])
d = set([11, 3, 23, 3, 4, 44])
set_list = [a, b, c, d]
Loop and save results
# I don't know what you want to do with the results so
# I'll save them in a list...
results = []
for i in set_list:
list_copy = list(set_list)
list_copy.remove(i)
r = i - functools.reduce(operator.or_, list_copy)
results.append(r)
print(results)
# prints [set(), {9, 7}, {8, 10, 12, 45}, {11, 44, 23}]
This is a re-implementation of NPE's answer using collections.Counter from the standard library:
from collections import Counter
def mutual_difference(set_list):
# create a multiset out of the union of all sets
union = Counter()
for s in set_list:
union.update(s)
new_set_list = []
for s in set_list:
# subtract s from the union and discard 0-count elements
union.subtract(s)
union += {}
# take the difference
new_set_list.append(s.difference(union))
# add s to the union again
union.update(s)
return new_set_list
Example:
>>> mutual_difference([{1,2}, {2,3}, {1,4,5}])
[set(), {3}, {4, 5}]
[value - {item for subset in set_list[0:index] + set_list[index + 1:] for item in subset} for index, value in enumerate(set_list)]
which means:
result = []
for index, value in enumerate(set_list):
union = {
item
for subset in set_list[0:index] + set_list[index + 1:]
for item in subset
}
result.append(value - union)
print(result)
Outputs:
[set(), {9, 7}, {8, 10, 12, 45}, {11, 44, 23}]

Convert dictionary into list with length based on values

I have a dictionary
d = {1: 3, 5: 6, 10: 2}
I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.
I've written this code that does the job:
d = {1: 3, 5: 6, 10: 2}
l = []
for i in d:
for j in range(d[i]):
l.append(i)
l.sort()
print(l)
Output:
[1, 1, 1, 5, 5, 5, 5, 5, 5, 10, 10]
But I would like it to be a list comprehension. How can this be done?
You can do it using a list comprehension:
[i for i in d for j in range(d[i])]
yields:
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
You can sort it again to get the list you were looking for.
[k for k,v in d.items() for _ in range(v)]
... I guess...
if you want it sorted you can do
[k for k,v in sorted(d.items()) for _ in range(v)]
One approach is to use itertools.chain to glue sublists together
>>> list(itertools.chain(*[[k]*v for k, v in d.items()]))
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
Or if you are dealing with a very large dictionary, then you could avoid constructing the sub lists with itertools.chain.from_iterable and itertools.repeat
>>> list(itertools.chain.from_iterable(itertools.repeat(k, v) for k, v in d.items()))
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
Comparative timings for a very large dictionary with using a list comprehension that uses two loops:
>>> d = {i: i for i in range(100)}
>>> %timeit list(itertools.chain.from_iterable(itertools.repeat(k, v) for k, v in d.items()))
10000 loops, best of 3: 55.6 µs per loop
>>> %timeit [k for k, v in d.items() for _ in range(v)]
10000 loops, best of 3: 119 µs per loop
It's not clear whether you want your output sorted (your example code does not sort it), but if so simply presort d.items()
# same as previous examples, but we sort d.items()
list(itertools.chain(*[[k]*v for k, v in sorted(d.items())]))
Counter.elements() method does exactly this:
from collections import Counter
d = {1: 3, 5: 6, 10: 2}
c = Counter(d)
result = list(c.elements())
print(result)
# [1, 1, 1, 5, 5, 5, 5, 5, 5, 10, 10]

Create dictionary where keys are from a list and values are the sum of corresponding elements in another list

I have two lists L1 and L2. Each unique element in L1 is a key which has a value in the second list L2. I want to create a dictionary where the values are the sum of elements in L2 that are associated to the same key in L1.
I did the following but I am not very proud of this code. Is there any simpler pythonic way to do it ?
L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
W = range(len(L)) # as L2
d = { l:[] for l in L }
for l,w in zip(L,W): d[l].append(w)
d = {l:sum(v) for l,v in d.items()}
EDIT:
Q: How do I know which elements of L2 are associated to a given key element of L1?
A: if they have the same index. For example if the element 7 is repeated 3 times in L1 (e.g. L1[2] == L1[7] == L1[8] = 7), then I want the value of the key 7 to be L2[2]+L2[7]+L2[8]
You can use enumerate() in order to access to item's index while you loop over the list and use collections.defaultdict() (by passing the int as it's missing function which will be evaluated as 0 at first time) to preserve the items and add the values while encounter a duplicate key:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i,j in enumerate(L):
... d[j]+=i
...
>>> d
defaultdict(<type 'int'>, {2: 6, 3: 4, 4: 15, 5: 5, 7: 17, 8: 9, 9: 10})
If you don't need the intermediate dict of lists you can use the collections.Counter:
import collections
L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
W = range(len(L)) # as L2
d2 = collections.Counter()
for i, value in enumerate(L):
d2[value] += i
which behaves like a normal dict:
Counter({2: 6, 3: 4, 4: 15, 5: 5, 7: 17, 8: 9, 9: 10})
Hope this may help you.
L = [2, 3, 7, 3, 4, 5, 2, 7, 7, 8, 9, 4] # as L1
dict_a = dict.fromkeys(set(L),0)
for l,w in enumerate(L):
dict_a[w] = int(dict_a[w]) + l

How to count the frequency of the elements in an unordered list? [duplicate]

This question already has answers here:
Using a dictionary to count the items in a list
(8 answers)
Closed 7 months ago.
Given an unordered list of values like
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
How can I get the frequency of each value that appears in the list, like so?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
In Python 2.7 (or newer), you can use collections.Counter:
>>> import collections
>>> a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
>>> counter = collections.Counter(a)
>>> counter
Counter({1: 4, 2: 4, 5: 2, 3: 2, 4: 1})
>>> counter.values()
dict_values([2, 4, 4, 1, 2])
>>> counter.keys()
dict_keys([5, 1, 2, 4, 3])
>>> counter.most_common(3)
[(1, 4), (2, 4), (5, 2)]
>>> dict(counter)
{5: 2, 1: 4, 2: 4, 4: 1, 3: 2}
>>> # Get the counts in order matching the original specification,
>>> # by iterating over keys in sorted order
>>> [counter[x] for x in sorted(counter.keys())]
[4, 4, 2, 1, 2]
If you are using Python 2.6 or older, you can download an implementation here.
If the list is sorted, you can use groupby from the itertools standard library (if it isn't, you can just sort it first, although this takes O(n lg n) time):
from itertools import groupby
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
[len(list(group)) for key, group in groupby(sorted(a))]
Output:
[4, 4, 2, 1, 2]
Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates.
>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]
Count the number of appearances manually by iterating through the list and counting them up, using a collections.defaultdict to track what has been seen so far:
from collections import defaultdict
appearances = defaultdict(int)
for curr in a:
appearances[curr] += 1
In Python 2.7+, you could use collections.Counter to count items
>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]
Counting the frequency of elements is probably best done with a dictionary:
b = {}
for item in a:
b[item] = b.get(item, 0) + 1
To remove the duplicates, use a set:
a = list(set(a))
You can do this:
import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)
Output:
(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))
The first array is values, and the second array is the number of elements with these values.
So If you want to get just array with the numbers you should use this:
np.unique(a, return_counts=True)[1]
Here's another succint alternative using itertools.groupby which also works for unordered input:
from itertools import groupby
items = [5, 1, 1, 2, 2, 1, 1, 2, 2, 3, 4, 3, 5]
results = {value: len(list(freq)) for value, freq in groupby(sorted(items))}
results
format: {value: num_of_occurencies}
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
I would simply use scipy.stats.itemfreq in the following manner:
from scipy.stats import itemfreq
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq = itemfreq(a)
a = freq[:,0]
b = freq[:,1]
you may check the documentation here: http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html
from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]
counter=Counter(a)
kk=[list(counter.keys()),list(counter.values())]
pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.
Suppose we have a list:
fruits = ['banana', 'banana', 'apple', 'banana']
We can find out how many of each fruit we have in the list like so:
import numpy as np
(unique, counts) = np.unique(fruits, return_counts=True)
{x:y for x,y in zip(unique, counts)}
Result:
{'banana': 3, 'apple': 1}
This answer is more explicit
a = [1,1,1,1,2,2,2,2,3,3,3,4,4]
d = {}
for item in a:
if item in d:
d[item] = d.get(item)+1
else:
d[item] = 1
for k,v in d.items():
print(str(k)+':'+str(v))
# output
#1:4
#2:4
#3:3
#4:2
#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}
For your first question, iterate the list and use a dictionary to keep track of an elements existsence.
For your second question, just use the set operator.
def frequencyDistribution(data):
return {i: data.count(i) for i in data}
print frequencyDistribution([1,2,3,4])
...
{1: 1, 2: 1, 3: 1, 4: 1} # originalNumber: count
I am quite late, but this will also work, and will help others:
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq_list = []
a_l = list(set(a))
for x in a_l:
freq_list.append(a.count(x))
print 'Freq',freq_list
print 'number',a_l
will produce this..
Freq [4, 4, 2, 1, 2]
number[1, 2, 3, 4, 5]
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counts = dict.fromkeys(a, 0)
for el in a: counts[el] += 1
print(counts)
# {1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
# 1. Get counts and store in another list
output = []
for i in set(a):
output.append(a.count(i))
print(output)
# 2. Remove duplicates using set constructor
a = list(set(a))
print(a)
Set collection does not allow duplicates, passing a list to the set() constructor will give an iterable of totally unique objects. count() function returns an integer count when an object that is in a list is passed. With that the unique objects are counted and each count value is stored by appending to an empty list output
list() constructor is used to convert the set(a) into list and referred by the same variable a
Output
D:\MLrec\venv\Scripts\python.exe D:/MLrec/listgroup.py
[4, 4, 2, 1, 2]
[1, 2, 3, 4, 5]
Simple solution using a dictionary.
def frequency(l):
d = {}
for i in l:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
for k, v in d.iteritems():
if v ==max (d.values()):
return k,d.keys()
print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
#!usr/bin/python
def frq(words):
freq = {}
for w in words:
if w in freq:
freq[w] = freq.get(w)+1
else:
freq[w] =1
return freq
fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()
from collections import OrderedDict
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
def get_count(lists):
dictionary = OrderedDict()
for val in lists:
dictionary.setdefault(val,[]).append(1)
return [sum(val) for val in dictionary.values()]
print(get_count(a))
>>>[4, 4, 2, 1, 2]
To remove duplicates and Maintain order:
list(dict.fromkeys(get_count(a)))
>>>[4, 2, 1]
i'm using Counter to generate a freq. dict from text file words in 1 line of code
def _fileIndex(fh):
''' create a dict using Counter of a
flat list of words (re.findall(re.compile(r"[a-zA-Z]+"), lines)) in (lines in file->for lines in fh)
'''
return Counter(
[wrd.lower() for wrdList in
[words for words in
[re.findall(re.compile(r'[a-zA-Z]+'), lines) for lines in fh]]
for wrd in wrdList])
For the record, a functional answer:
>>> L = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> import functools
>>> >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc,1)] if e<=len(acc) else acc+[0 for _ in range(e-len(acc)-1)]+[1], L, [])
[4, 4, 2, 1, 2]
It's cleaner if you count zeroes too:
>>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc)] if e<len(acc) else acc+[0 for _ in range(e-len(acc))]+[1], L, [])
[0, 4, 4, 2, 1, 2]
An explanation:
we start with an empty acc list;
if the next element e of L is lower than the size of acc, we just update this element: v+(i==e) means v+1 if the index i of acc is the current element e, otherwise the previous value v;
if the next element e of L is greater or equals to the size of acc, we have to expand acc to host the new 1.
The elements do not have to be sorted (itertools.groupby). You'll get weird results if you have negative numbers.
Another approach of doing this, albeit by using a heavier but powerful library - NLTK.
import nltk
fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()
Found another way of doing this, using sets.
#ar is the list of elements
#convert ar to set to get unique elements
sock_set = set(ar)
#create dictionary of frequency of socks
sock_dict = {}
for sock in sock_set:
sock_dict[sock] = ar.count(sock)
For an unordered list you should use:
[a.count(el) for el in set(a)]
The output is
[4, 4, 2, 1, 2]
Yet another solution with another algorithm without using collections:
def countFreq(A):
n=len(A)
count=[0]*n # Create a new list initialized with '0'
for i in range(n):
count[A[i]]+= 1 # increase occurrence for value A[i]
return [x for x in count if x] # return non-zero count
num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)
You can use the in-built function provided in python
l.count(l[i])
d=[]
for i in range(len(l)):
if l[i] not in d:
d.append(l[i])
print(l.count(l[i])
The above code automatically removes duplicates in a list and also prints the frequency of each element in original list and the list without duplicates.
Two birds for one shot ! X D
This approach can be tried if you don't want to use any library and keep it simple and short!
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)
o/p
[4, 4, 2, 1, 2]

Categories

Resources