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

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

问题描述

所以我想用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.

推荐答案

有这里有问题了一把:


  1. 您正在尝试遍历 fizz_count 。但 fizz_count 是函数。 X 是传入的参数。所以,它应该是在X X:(但见#3)

  2. 您正在接受与一个参数* X 。在 * 引起 X 成为的所有的参数的元组。如果你只传递一个,一个列表,那么该列表是 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)

但事实上列表有一个计数()的方法一样,元组,所以如果你肯定知道你的论点是一个列表或元组(而不是其他类型的序列),你可以做:

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天全站免登陆