python-3.x 从字符列表中计算字符串中的字符数

agyaoht7  于 2022-11-26  发布在  Python
关注(0)|答案(6)|浏览(223)

我正在尝试编写一个函数count(s, chars),它接受字符串s和字符列表chars。该函数应该计算chars中给定字母的出现次数。它应该返回一个字典,其中的键是字符列表chars中给定的字符。
例如:

In [1]: s = "Another test string with x and y but no capital h."
In [2]: count(s, ['A', 'a', 'z'])
Out[2]: 'A': 1, 'a': 3, 'z': 0

我做了一些代码,可以计算字符串的所有字符,并返回一个字典:

return {i: s.count(i) for i in set(s)}

但我不确定如何使用特定字符列表并返回字典。

zysjyyx4

zysjyyx41#

关于:

def count_chars(s,chars):
    return {c : s.count(c) for c in chars}

生成:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "Another test string with x and y but no capital h."
>>> def count_chars(s,chars):
...     return {c : s.count(c) for c in chars}
... 
>>> count_chars(s, ['A', 'a', 'z'])
{'z': 0, 'A': 1, 'a': 3}

虽然这是相当低效的。也许更有效的方法是在一个步骤中完成计数。你可以使用Counter来完成这项工作,然后保留有趣的字符:

from collections import Counter

def count_chars(s,chars):
    counter = Counter(s)
    return {c : counter.get(c,0) for c in chars}
xqnpmsa8

xqnpmsa82#

str.count(sub[, start[, end]])

返回子字符串sub在范围[start,end]中不重叠出现的次数。可选参数start和end在切片表示法中被解释为。
例如使用

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

所以count函数也可以很容易地用在这个场景中。

li=['A', 'a', 'z']
s = "Another test string with x and y but no capital h."

def count(s, li):
    cnt=dict.fromkeys(li, 0)
    for c in li:
      cnt[c] = s.count(c)
    return cnt

控制台输出如下所示

>>> count(s, li)
{'a': 3, 'A': 1, 'z': 0}
zpgglvta

zpgglvta3#

您可以使用dict fromkeys方法将所有关键字设置为零,然后为每个字符递增,以“旧方式”执行此操作:

li=['A', 'a', 'z']
s = "Another test string with x and y but no capital h."

def count(s, li):
    cnt={}.fromkeys(li, 0)
    for c in s:
        if c in cnt:
            cnt[c]=cnt[c]+1
    return cnt

>>> count(s, li)
{'A': 1, 'a': 3, 'z': 0}

或者,进行预筛选,以便只测试您感兴趣的键:

def count(s, li):
    cnt={}.fromkeys(li, 0)
    for c in (e for e in s if e in cnt):
        cnt[c]+=1
    return cnt

但最快、最多的Pythonic是使用Counter:

>>> from collections import Counter
>>> c=Counter(s)
>>> c
Counter({' ': 10, 't': 7, 'n': 4, 'h': 3, 'i': 3, 'a': 3, 'o': 2, 'e': 2, 'r': 2, 's': 2, 'A': 1, 'g': 1, 'w': 1, 'x': 1, 'd': 1, 'y': 1, 'b': 1, 'u': 1, 'c': 1, 'p': 1, 'l': 1, '.': 1})

然后根据这些内容构建你想要的法令:

>>> {k:c[k] for k in li}
{'A': 1, 'a': 3, 'z': 0}
68bkxrlz

68bkxrlz4#

def count(s, chars):
    ret = dict(zip(chars, [0 for c in chars]))
    for c in s:
        if ret.has_key(c):
            ret[c] += 1
    return ret

也许是类似的事。

atmip9wb

atmip9wb5#

你也可以用zip内置的方法构建字典:

>>> s
'Another test string with x and y but no capital h.'
>>> c
['A', 'a', 'z']
>>> def count_char(s, c):
       counts = map(s.count, c)
       return dict(zip(c, counts))

>>> 
>>> count_char(s, c)
{'z': 0, 'A': 1, 'a': 3}
iibxawm4

iibxawm46#

好吧,有这么多答案,我也会给出我的答案,它是基于内置的结构:

from collections import Counter

s = "Another test string with x and y but no capital h."
chars = ['A', 'a', 'z']

count = Counter(s)  # creates a dictionary
count = {k:v for k, v in count.items() if k in chars}  # take only charatcters from chars
count.update({k:0 for k in set(chars) - set(s)})  # add zero instances
print(count)

===
{'a': 3, 'A': 1, 'z': 0}

相关问题