2016-10-19 31 views
1

我正在尋找計算列表中字母數量的最有效方法。我需要這樣的東西在循環中使用字母作爲計數器

word=[h e l l o] 

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

字母應該是西班牙字母,即包括特殊字符「N」英文字母。

我曾想過以[[a,0],[b,1],...]的形式創建對列表,但我想有更高效/乾淨的方式。

+0

'word.count('ñ')'或更好'計數器(字)' – furas

回答

2

它實際上不是一個傻瓜,你要進行過濾,只算從一組特定的字符,你可以使用Counter字典做計數和一組允許字符過濾:

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

我不懂西班牙語。但根據我在互聯網上得到的信息,除了''以外,還有其他角色。檢查[這裏](http://sites.psu.edu/symbolcodes/languages/psu/spanish/) –

+0

@anonymous,*凡字母表應該是西班牙字母,那是**英文字母,包括特殊字符'ñ'。*這正是'ascii_lowercase +'ñ''的意思。 –

+1

@anonymous如果你指的是角色,我不會考慮那些角色。如果你正在考慮像'ch'或'll'這樣的字符,這些不再是西班牙字母表中的字符。 – D1X

0

這是很容易的:

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

此打印:

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