【问题标题】:Using alphabet as counter in a loop在循环中使用字母作为计数器
【发布时间】:2016-10-19 10:56:52
【问题描述】:

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

word=[h e l l o]

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

alphabet 应该是 spanish 字母表,即包含特殊字符 'ñ' 的英文字母表。

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

【问题讨论】:

  • word.count('ñ') 或更好的Counter(word)

标签: python list character


【解决方案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))

对于任何方法,使用 filter 都会更快一些:

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+ 'ñÑ')

【讨论】:

  • 我不懂西班牙语。但根据我在互联网上获得的信息,除了ñ 之外,它还有其他字符。检查here
  • @anonymous,其中字母应该是西班牙字母,即 english 字母,包括特殊字符 'ñ'。 这正是ascii_lowercase + 'ñ' 是。
  • @anonymous 如果您指的是字符 á é í ó ú ü,我不考虑这些。如果您正在考虑诸如“ch”或“ll”之类的字符,这些字符不再是西班牙字母表中的字符。
  • 如果word 中包含大写字母,这将不起作用 - 如果需要,counts = Counter(s.lower() for s in word if s.lower() in allowed) 会捕获它(至少对于英文字母)
  • @asingtoruin, map(str.lower, word) 或使用 ascii_letters 如果有要求的话会这样做。
【解决方案2】:

这很简单:

import collections
print collections.Counter("señor")

打印出来:

Counter({'s': 1, 'r': 1, 'e': 1, '\xa4': 1, 'o': 1})

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2013-12-04
    相关资源
    最近更新 更多