(Python 2.7) 在函数中使用列表作为参数? [英] (Python 2.7) Use a list as an argument in a function?
问题描述
所以我正在尝试使用 codecademy 学习 Python,但我被卡住了.它要求我定义一个将列表作为参数的函数.这是我的代码:
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".def 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
是你传入的参数.所以它应该是for x in x:
(但见 #3). - 您接受一个带有
*x
的参数.*
使x
成为 all 参数的元组.如果只传递一个,一个列表,那么列表是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)
但实际上 list
有一个 count()
方法,tuple
也是如此,所以如果你确定你的参数是一个列表或元组(而不是其他类型的序列),你可以这样做:
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) 在函数中使用列表作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!