如何快速将列表中的字母计数分配给Python中的变量

时间:2015-05-09 01:16:59

标签: python variables python-3.x count

基本上我有一个(用于所有意图和目的)随机字母的列表。这些字母并不是随机的,它们确实有意义;但是,这个问题真的不重要。列表看起来像这样:

list = ['v', 'f', 't', 'w', 'w', 'i', 'b']

真实列表显着更长(最多100个字符)。我想计算每个字母出现的次数,并将其分配给该字母的变量。例如:

a = list.count('a')
b = list.count('b')
c = list.count('c')
...
...
z = list.count('z')

我只是想知道是否有一种更简单的方法来执行此操作,而不是键入26次相同的行。我正在运行Python 3.4。我希望能够以尽可能少的行和尽可能少的字符来完成它。任何建议都会有所帮助,谢谢。

4 个答案:

答案 0 :(得分:2)

import collections

counts = collections.Counter(l)

counts['a']则是a的出现次数。如果列出了LN个可能不同的项目,则会在O(L)时间而不是O(NL)基于list.count的解决方案中运行,并且它的代码较少。

答案 1 :(得分:0)

简单方法#1

import string
x = string.ascii_lowercase #  'abcdefghijklmnopqrstuvwxyz'
l = ['v', 'f', 't', 'w', 'w', 'i', 'b']
d = {}
for i in x:
  d[i] = l.count(i)

稍微有点发作的方法#2

import string
x = string.ascii_lowercase #  'abcdefghijklmnopqrstuvwxyz'
l = ['v', 'f', 't', 'w', 'w', 'i', 'b']
d = dict([(i, l.count(i)) for i in x])

现在d将包含类似于:

的内容
{
  'a': 2,
  'b': 3,
  'c': 0,
  ...
} 

答案 2 :(得分:0)

此方法使用字典为每个字母分配计数,而不是使用实际的字母本身。

from collections import Counter
import string

dictionary = dict(Counter(l))

>>> dictionary
{'b': 1, 'f': 1, 'i': 1, 't': 1, 'v': 1, 'w': 2}

>>> dictionary['w']
2

如果您需要每个字母的完整字典,可以按如下方式扩展:

letters = string.ascii_lowercase
dictionary.update({c: 0 for c in letters if c not in dictionary})

>>>> dictionary
{'a': 0,
 'b': 1,
 'c': 0,
 'd': 0,
 'e': 0,
 'f': 1,
 'g': 0,
 'h': 0,
 'i': 1,
 'j': 0,
 'k': 0,
 'l': 0,
 'm': 0,
 'n': 0,
 'o': 0,
 'p': 0,
 'q': 0,
 'r': 0,
 's': 0,
 't': 1,
 'u': 0,
 'v': 1,
 'w': 2,
 'x': 0,
 'y': 0,
 'z': 0}

或者您可以简单地在原始字典上使用letter_count = dictionary.get(letter,0),以便为字典中没有的任何字母返回零。

答案 3 :(得分:0)

这是一种无需导入的方法。既然你说你期待多达100个字符,这仍然是一个小集合,我不会太担心计算复杂性成本。

list(set(zip(l,[l.count(x) for x in l])))