开发者

Passing a list of values to a function

Sorry for such a silly question, but sitting in front of the comp for many hours makes my head overheated, in other words — I'm totally confused. My task is to define a function that takes a list of words and returns something. How can I define a function that will take a list of words?

def function(list_of_words):
    do something

When running this script in Python IDLE we should su开发者_开发问答ppose to write something like this:

>>> def function('this', 'is', 'a', 'list', 'of', 'words')

But Python errors that the function takes one argument, and six (arguments) are given. I guess I should give my list a variable name, i.e. list_of_words = ['this', 'is', 'a', 'list', 'of', 'words'], but ... how?


Use code:

def function(*list_of_words):
     do something

list_of_words will be a tuple of arguments passed to a function.


Simply call your function with:

function( ['this', 'is', 'a', 'list', 'of', 'words'] )

This is passing a list as an argument.


It's simple:

list_of_words = ['this', 'is', 'a', 'list', 'of', 'words']
def function(list_of_words):
    do_something

That's all there is to it.


>>> def function(list_of_words):
...     print( list_of_words )
... 
>>> 
>>> function('this', 'is', 'a', 'list', 'of', 'words')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() takes exactly 1 argument (6 given)
>>> function(['this', 'is', 'a', 'list', 'of', 'words'])
['this', 'is', 'a', 'list', 'of', 'words']

Works for me. What's going wrong for you? Can you be specific on what doesn't work for you?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜