Issue
list = ('S', 'S', 'C', 'R', 'C', 'R', 'S', 'C', 'C', 'R', 'S', 'C', 'S', 'S', 'R', 'C', 'R', 'C', 'C', 'S', 'R')
list1 = []
for i in list:
if i == 'C':
list1.append('C')
print(list1)
So I was trying to create a empty list and add only 'C'
into list1. And calculate how many 'C'
are in the list1. Iteration of over the list and len(list1)
but that would give me all the len
of my iteration... what are easier ways of calculating numbers of only'C'
in list1? without iteration?
Thanks in advance.
Solution
You have many ways to solve this:
classical loop
my_list = ('S', 'S', 'C', 'R', 'C', 'R', 'S', 'C', 'C', 'R', 'S', 'C', 'S', 'S', 'R', 'C', 'R', 'C', 'C', 'S', 'R')
i = 0
for letter in my_list:
if letter == 'C':
i+=1
print(i)
list comprehension
>>> len([None for i in my_list if i == 'C'])
8
filter
NB. this might be most useful to count not strictly identical objects
>>> len(list(filter('C'.__eq__, my_list)))
8
collections.Counter
(already proposed by @eduardosufan)
from collections import Counter
Counter(my_list)['C']
output: 8
list.count
method
>>> my_list.count('C')
8
Answered By - mozway Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.