0

Based on this answer, I am using this to count the occurrences of letters in a word:

mylist = list("asmoranomardicadaistinaculdacar")

[[x,mylist.count(x)] for x in set(mylist)]

which gives:

[['n', 2],
 ['r', 3],
 ['u', 1],
 ['m', 2],
 ['t', 1],
 ['a', 8],
 ['l', 1],
 ['s', 2],
 ['o', 2],
 ['i', 3],
 ['c', 3],
 ['d', 3]]

What is the best way to filter these results based on the number of occurrences of each letter? Say if I wanted to keep only the letter that have a count of 3 or greater?

I feel like there's a clean one-liner that will get me what I'm looking for, but I'm not good enough at Python to write it myself...

Whitehot
  • 383
  • 3
  • 19

3 Answers3

2

You can add an if statement along:

mylist = list("asmoranomardicadaistinaculdacar")

[[x,mylist.count(x)] for x in set(mylist) if mylist.count(x)>2]
Kedar U Shet
  • 538
  • 2
  • 11
1

How about [ch for ch in set(mylist) if mylist.count(ch) >= 3]?

MMZK1526
  • 654
  • 2
  • 16
1

If you're using Python 3.8 and above improve it by calling count one time and storing result using the walrus operator:

mylist = list("asmoranomardicadaistinaculdacar")

print([[x, cn] for x in set(mylist) if (cn := mylist.count(x)) > 2])

Output:

[['a', 8], ['d', 3], ['i', 3], ['c', 3], ['r', 3]]
funnydman
  • 9,083
  • 4
  • 40
  • 55