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.
CodePudding user response:
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
CodePudding user response:
Use collections counter https://docs.python.org/3/library/collections.html#collections.Counter to count the number of "C" without iteration:
from collections import Counter
list = ('S', 'S', 'C', 'R', 'C', 'R', 'S', 'C', 'C', 'R', 'S', 'C', 'S', 'S', 'R', 'C', 'R', 'C', 'C', 'S', 'R')
c = Counter(list)
print(c)
print(c["C"])
Result:
Counter({'C': 8, 'S': 7, 'R': 6})
8
CodePudding user response:
so if your just looking to count how many "c" 's there are you could just edit your code to:
for i in list:
if i == 'C':
list1.append('C')
x = x 1
print(x)