(Python 2.7) 在函数中使用列表作为参数? [英] (Python 2.7) Use a list as an argument in a function?

查看:29
本文介绍了(Python 2.7) 在函数中使用列表作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试使用 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.

推荐答案

这里有一些问题:

  1. 您正在尝试遍历 fizz_count.但是 fizz_count 是你的功能.x 是你传入的参数.所以它应该是 for x in x:(但见 #3).
  2. 您接受一个带有 *x 的参数.* 使 x 成为 all 参数的元组.如果只传递一个,一个列表,那么列表是x[0],列表的项目是x[0][0],x[0][1] 等等.更容易接受 x.
  3. 您正在使用参数 x 作为迭代列表中项目的占位符,这意味着在循环之后,x 不再引用到传入的列表,但到它的最后一项.在这种情况下这实际上会起作用,因为之后您不会使用 x,但为了清楚起见,最好使用不同的变量名称.
  4. 您的某些变量名称可能更具描述性.
  1. You're trying to iterate over fizz_count. But fizz_count is your function. x is your passed-in argument. So it should be for x in x: (but see #3).
  2. You're accepting one argument with *x. The * causes x to be a tuple of all arguments. If you only pass one, a list, then the list is x[0] and items of the list are x[0][0], x[0][1] and so on. Easier to just accept x.
  3. 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 use x afterward, but for clarity it's better to use a different variable name.
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆