Home > Software design >  Filter results of counted items
Filter results of counted items

Time:08-09

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...

CodePudding user response:

You can add an if statement along:

mylist = list("asmoranomardicadaistinaculdacar")

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

CodePudding user response:

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

CodePudding user response:

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]]
  • Related