问题描述
所以我想用codecademy学习Python,但我坚持。它要求我定义一个函数,它接受一个列表作为参数。这是code我有:
So I'm trying to learn Python using codecademy but I'm stuck. It's asking me to define a function that takes a list as an argument. This is the code I have:
# Write your function below!
def fizz_count(*x):
count = 0
for x in fizz_count:
if x == "fizz":
count += 1
return count
这也可能是一些愚蠢的事我做错了,但它不断告诉我,以确保功能只需要一个参数,X。 高清fizz_count(X):
不工作,要么虽然。我到底在这里做什么?
It's probably something stupid I've done wrong, but it keeps telling me to make sure the function only takes one parameter, "x". def fizz_count(x):
doesn't work either though. What am I supposed to do here?
编辑:感谢大家的帮助,我明白我正在做的事情是错误的。
Thanks for the help everyone, I see what I was doing wrong now.
推荐答案
有这里有问题了一把:
- 您正在尝试遍历
fizz_count
。但fizz_count
是函数。X
是传入的参数。所以,它应该是在X X:
(但见#3) - 您正在接受与
一个参数* X
。在*
引起X
成为的所有的参数的元组。如果你只传递一个,一个列表,那么该列表是X [0]
和列表项X [0] [0]
,X [0] [1]
等。容易只是接受X
。 - 您正在使用你的说法,
X
,作为占位符列表中的项目,当你迭代它,这意味着在循环后,X
不再引用传入的名单,但它的最后一个项目。这将在这种情况下,实际的工作,因为你不使用X
之后,但为清楚起见,最好使用不同的变量名。 - 你的一些变量名可以更具描述性。
- You're trying to iterate over
fizz_count
. Butfizz_count
is your function.x
is your passed-in argument. So it should befor x in x:
(but see #3). - You're accepting one argument with
*x
. The*
causesx
to be a tuple of all arguments. If you only pass one, a list, then the list isx[0]
and items of the list arex[0][0]
,x[0][1]
and so on. Easier to just acceptx
. - You're using your argument,
x
, as the placeholder for items in your list when you iterate over it, which means after the loop,x
no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't usex
afterward, but for clarity it's better to use a different variable name. - Some of your variable names could be more descriptive.
把这些大家一起得到的东西是这样的:
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
我假设你正在做的很长的路要走一轮学习海豚,不游这么快。一个更好的方式来写,这可能是:
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
但事实上列表
有一个计数()
的方法一样,元组
,所以如果你肯定知道你的论点是一个列表或元组(而不是其他类型的序列),你可以做:
But in fact list
has a count()
method, as does tuple
, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
事实上,这是如此简单,你几乎需要编写一个函数吧!
In fact, that's so simple, you hardly need to write a function for it!
这篇关于(Python 2.7版)使用列表作为函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!