python 多个字符串怎样提取相同字符数量

字符串'123904560','23239504','2314564','78349088','7649643'
五个字符串.比如提取0在五个字符串内出现了三次 9在五个字符串内出现了4次
是否有简洁的方法,还是只能用遍历

阅读 6.5k
4 个回答

可以使用Counter

from collections import Counter
l = ['123904560', '23239504', '2314564', '78349088', '7649643']
counter = Counter()
for s in l:
    counter.update(set(s))
print(counter['0'])
print(counter['9'])

或者用filter

l = ['123904560', '23239504', '2314564', '78349088', '7649643']
print(len(list(filter(lambda x: x.find('0') != -1, l))))

[''.join(['123904560','23239504','2314564','78349088','7649643']).count(i) for i in ['0', '9']]

可以用正则表达式

>>> import re
>>> re.findall(r'0', '123904560')
['0', '0']
>>> print len(re.findall(r'0', '123904560'))
2

希望可以帮助到你。

>>> from collections import Counter
>>> s = ['123904560', '23239504', '2314564', '78349088', '7649643']
>>> count = lambda i: Counter(''.join(s)).get(str(i))
>>> count(1)
2
>>> count(0)
4
>>> count(9)
4
>>> 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题