0

In this question, I want to ask how to count specific character in list using python:

The example of list are following below:

aList = [123, 'Xyz', 'zaRa', 'Abc', 123];

How to count "X", "R", "A" characters in that list?

The desired output is following below:

X = 1
R = 1
A = 1

3 Answers 3

2

Map every element to a string, then stick them all together, then use the count() string method.

aList = [123, 'Xyz', 'zaRa', 'Abc', 123]
mystring = ''.join(map(str, aList))
for letter in 'XRA':
    print('{} = {}'.format(letter, mystring.count(letter)))
Sign up to request clarification or add additional context in comments.

Comments

1

I would use collections.Counter , something like this -

>>> from collections import Counter
>>> aList = [123, 'Xyz', 'zaRa', 'Abc', 123]
>>> astr = ''.join(map(str,aList))
>>> Counter(astr)
Counter({'3': 2, 'z': 2, 'a': 2, '2': 2, '1': 2, 'A': 1, 'X': 1, 'R': 1, 'b': 1, 'c': 1, 'y': 1})
>>> c = Counter(astr)
>>> c['X']
1
>>> c['R']
1
>>> c['A']
1

Comments

-2
In [6]: ''.join([ item for item in aList if type(item) == str ]).count('X')
Out[6]: 1

In [7]: ''.join([ item for item in aList if type(item) == str ]).count('R')
Out[7]: 1

In [8]: ''.join([ item for item in aList if type(item) == str ]).count('A')
Out[8]: 1

1 Comment

Please explain what your code does and why it will solve the problem. An answer that just contains code (even if it's working) usually wont help the OP to understand their problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.