Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python函数错误_Python_Function - Fatal编程技术网

Python函数错误

Python函数错误,python,function,Python,Function,我写了一个简单的函数程序。程序本身工作,但当转换为函数时,它给出的字符计数为1。我使用的是Python版本3.5 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','

我写了一个简单的函数程序。程序本身工作,但当转换为函数时,它给出的字符计数为1。我使用的是Python版本3.5

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')

如果开始时覆盖了x,y的值,请重试

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')
此外,我们还可以通过从中获取价值、在外部打印和使用

最后,我们可以使用以下方法:

Python有一个计数器对象可以执行此操作,对于尚未看到的值,计数器返回0,简单来说就是:

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

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

这是真的,是的,但这不是有点武断吗?计数器本身就是一个函数。。我不确定我是否理解这个问题。计数器是一种类型,类似于multisetDefault。如果setdefault使用得不多,可以使用collections.defaultdictent进行计数,也可以使用count[char]=count.getchar,0+1
def sink3(x, y):
    return ''.join(x).count(y)


print(sink3(['a', 'a', 'c', 'd', 'e', 'e'], 'e'))
from collections import Counter
def sink(x, y):
    return Counter(x)[y]

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