2017-06-03 77 views
0

我写了一个简单的函数程序。该程序本身工作,但转换为函数时,它给出的字符数为1.我正在使用Python版本3.5。Python函数错误

def sink(x,y): 
    x = ['a','a','b','c'] 
    y = 'c' 

    count = {} 
    for char in x: 
    count.setdefault(char,0) 
    count[char] = count[char]+1 
    print (count.get(y,0)) 



sink (['a','a','c','d','e','e'],'e') 
+0

不是一个伟大的使用setdefault'的',你可以使用' collections.defaultdict(int)'为'count'或者只是'count [char] = count.get(char,0)+ 1' – AChampion

回答

7

你在一开始重写的xy值,尝试

def sink(x, y): 
    count = {} 
    for char in x: 
     count.setdefault(char, 0) 
     count[char] = count[char] + 1 
    print(count.get(y, 0)) 


sink(['a', 'a', 'c', 'd', 'e', 'e'], 'e') 

我们也可以通过它returning值和印刷外,并使用augmented arithmetic assignment +=

def sink2(x, y): 
    count = {} 
    for char in x: 
     count.setdefault(char, 0) 
     count[char] += 1 
    return count.get(y, 0) 


print(sink(['a', 'a', 'c', 'd', 'e', 'e'], 'e')) 
提高你的函数

终于我们可以用str.joinstr.count方法:

def sink3(x, y): 
    return ''.join(x).count(y) 


print(sink3(['a', 'a', 'c', 'd', 'e', 'e'], 'e')) 
+0

完美。谢谢你。 – Vish

+0

@Vish:如果没问题,您可以[接受答案](https://stackoverflow.com/help/someone-answers) –

+0

接受。先生,再次谢谢你。 – Vish

0

Python有一个Counter对象,这是否和Counter返回0不已经出现了价值,所以很简单:

from collections import Counter 
def sink(x, y): 
    return Counter(x)[y] 

>>> sink(['a','a','c','d','e','e'], 'e') 
2 
+0

这是真的,是的,但不是有点武断吗? '计数器'本身就是一个函数..大声笑 – Mangohero1

+0

不知道我明白这个问题。 “计数器”是一种类型,类似于多重集合 – AChampion