从字符列表

时间:2017-01-15 18:07:40

标签: python python-3.x

我正在尝试编写一个带有字符串count(s, chars)和a的函数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)}

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

6 个答案:

答案 0 :(得分:5)

怎么样:

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}

答案 1 :(得分:2)

你可以做到这一点'旧式'通过使用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}

或者,prefilter所以你只测试你感兴趣的键:

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都是使用计数器:

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

答案 2 :(得分:2)

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

返回子字符串sub的非重叠出现次数   范围[开始,结束]。可选参数start和end是   解释为切片表示法。

e.g。使用

>>> 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={}.fromkeys(li, 0)
    for c in li:
      cnt[c] = s.count(c);
    return cnt

控制台输出将类似于

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

答案 3 :(得分:1)

 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

可能是这样的。

答案 4 :(得分:1)

您还可以使用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}

答案 5 :(得分:1)

嗯,这么多的答案,我也会投入我的,这是基于内置的结构:

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}