How to Count the Frequency of the Elements in an Unordered List

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

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]

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

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]

frequency of all elements of list in Python

Use collection's Counter:

>>> from collections import Counter
>>> l = [1,2,2,3,1,1,2,3,4,5,6]
>>> Counter(l)
Counter({1: 3, 2: 3, 3: 2, 4: 1, 5: 1, 6: 1})

Pythonic way to count the most frequent items with duplicates in Counter, separately by number of elements?

This is O(n) and I don't think it will be possible to get asymptotically any better than that.

highest_count_for_length = {}
result = []
for tup, count in d.items():
try:
if highest_count_for_length[len(tup)] == count:
result.append(tup)
except KeyError:
# we haven't seen this length yet
highest_count_for_length[len(tup)] = count
result.append(tup)

It does rely on the fact that the input is already ordered by value.

How to get the count of elements in each unordered HTML list on a page with multiple lists present?

Try the following code.It will first find all <ul> tag and then find linked <li> tag

 elements=driver.find_elements_by_tag_name('ul')
#print(len(elements))
for ele in elements:
print(len(ele.find_elements_by_xpath("./li")))

Output:

2
3
4

Getting the Frequency of Elements in a Table With Respect to Another Column

As Shubham commented, you can cross tabulate:

import pandas as pd
df = pd.DataFrame({
'Patient': ['Ralph', 'Ralph', 'Steve'],
'Diagnosis': ['A', 'A', 'B'],
})
pd.crosstab(df.Patient, df.Diagnosis)

Output:

Diagnosis   A   B
Patient
Ralph 2 0
Steve 0 1

R: Count frequency of values in nested list with sub-elements

One way with lapply(), unlist() and table():

count <- table(unlist(lapply(lst, unique)))
count
# Austria Japan Sweden
# 5 1 2


as.data.frame(count)
# Var1 Freq
# 1 Austria 5
# 2 Japan 1
# 3 Sweden 2

Reproducible data (please provide yourself next time):

lst <- list(
c('Austria', 'Austria', 'Austria'),
c("Austria", "Sweden"),
c("Austria", "Austria", "Sweden", "Sweden", "Sweden", "Sweden"),
c("Austria", "Austria", "Austria"),
c("Austria", "Japan")
)


Related Topics



Leave a reply



Submit