计算列表中的特定字符[python]

时间:2015-08-13 02:35:44

标签: python

在这个问题中,我想问一下如何使用python计算列表中的特定字符:

列表的示例如下:

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

如何计算该列表中的“X”,“R”,“A”字符?

所需的输出如下:

X = 1
R = 1
A = 1

3 个答案:

答案 0 :(得分:2)

将每个元素映射到一个字符串,然后将它们全部粘贴在一起,然后使用count()字符串方法。

aList = [123, 'Xyz', 'zaRa', 'Abc', 123]
mystring = ''.join(map(str, aList))
for letter in 'XRA':
    print('{} = {}'.format(letter, mystring.count(letter)))

答案 1 :(得分:1)

我会使用collections.Counter,就像这样 -

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

答案 2 :(得分:-1)

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