2016-11-09 116 views
0

我寫了這個功能:使用lambda功能和字典顯示功能,可以用不同的方式

def make_upper(words): 
    for word in words: 
     ind = words.index(word) 
     words[ind] = word.upper() 

但我需要使用哪個我不熟悉lambda函數寫。有任何想法嗎?

我還寫道,計算每個字母出現的頻率的函數:

def letter_cnt(word,freq): 
    for let in word: 
     if let == 'A': freq[0]+=1 
     elif let == 'B': freq[1]+=1 
     elif let == 'C': freq[2]+=1 
     elif let == 'D': freq[3]+=1 
     elif let == 'E': freq[4]+=1 

所以我需要用字典來寫。有什麼建議麼?

回答

0
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> words = ['werfwr', 'fwerw', 'ghebe', 'wgergwtg', 'gbeyteb'] 
>>> def make_upper(words): 
...  return map(lambda word: word.upper(), words) 
... 
>>> make_upper(words) 
['WERFWR', 'FWERW', 'GHEBE', 'WGERGWTG', 'GBEYTEB'] 
>>> def letter_cnt(word): 
...  letters = {} 
...  for symbol in word: 
...   symbol = symbol.lower() 
...   if 'a' <= symbol and symbol <= 'z': 
...    if symbol in letters: 
...     letters[symbol] += 1 
...    else: 
...     letters[symbol] = 1 
...  return letters 
... 
>>> letter_cnt('werfervt') 
{'e': 2, 'f': 1, 'r': 2, 't': 1, 'w': 1, 'v': 1}