python - 在循环中使用字母表作为计数器

标签 python list character

我正在寻找计算列表中字母数量的最有效方法。我需要类似的东西

word=[h e l l o]

for i in alphabet:
   for j in word:
      if j==i:
         ## do something

其中字母表应该是西类牙语字母表,即英语字母表,包括特殊字符'ñ'

我考虑过以 [[a, 0], [b,1], ...] 的形式创建一个对列表,但我认为有一种更有效/干净的方法。

最佳答案

它实际上并不是一个骗局,因为您想过滤以仅计算某个集合中的字符,您可以使用 Counter dict 进行计数和一组允许的字符进行过滤:

word = ["h", "e", "l", "l", "o"]

from collections import Counter
from string import ascii_lowercase

# create a set of the characters you want to count.
allowed = set(ascii_lowercase + 'ñ')

# use a Counter dict to get the counts, only counting chars that are in the allowed set.
counts = Counter(s for s in word if s in allowed)

如果您实际上只想要总金额:

total = sum(s in allowed for s in word)

或者使用函数式方法:

total = sum(1 for _ in filter(allowed.__contains__, word))

使用过滤器对于任何方法来说都会更快一些:

In [31]: from collections import Counter
    ...: from string import ascii_lowercase, digits
    ...: from random import choice
    ...: 

In [32]: chars = [choice(digits+ascii_lowercase+'ñ') for _ in range(100000)]

In [33]: timeit Counter(s for s in chars if s in allowed)

100 loops, best of 3: 36.8 ms per loop


In [34]: timeit Counter(filter(allowed.__contains__, chars))
10 loops, best of 3: 31.7 ms per loop

In [35]: timeit sum(s in allowed for s in chars)
10 loops, best of 3: 35.4 ms per loop

In [36]: timeit sum(1 for _ in filter(allowed.__contains__, chars))

100 loops, best of 3: 32 ms per loop

如果您想要不区分大小写的匹配,请使用 ascii_letters 并添加 'ñÑ':

from string import ascii_letters

allowed = set(ascii_letters+ 'ñÑ')

关于python - 在循环中使用字母表作为计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40129447/

相关文章:

list - LISP中列表元素的递归处理

list - 对象引用未设置为对象的实例- “Object includes a list property”

javascript - 如何在 JavaScript 中使用模运算符 (%)?

python - 从python3中的数组中删除元素

python - 获取上传到 Flask 的文件路径

java - 为什么一个列表给了我一个值,而另一个却没有?

java - 如何在Java中更改 'character set'?

python - 如何使用 python 脚本的输出作为 RASA 的输入而不是通常的用户输入?

python - 从正在运行的解释器启用 Sympy 自动符号模式

c# - 如何限制文本框仅接受特定字符