简体   繁体   English

使用列表作为python中的函数定义参数

[英]Use list as function definition parameters in python

Some similar questions have been answered here, but they all pertain to using a list as a variable within the function. 这里已经回答了一些类似的问题,但是它们都与将列表用作函数中的变量有关。 I am looking to use a list as the function definition: 我正在寻找使用列表作为函数定义:

varlist = ('a',
            'b',
            'c',
            'd',
            'e')

def func(*input):
    output = ""
    for item in input:
        output += item
    return output

a = "I'll "
b = "have "
c = "a "
d = "cheese "
e = "sandwich."

print func(*varlist)

This returns abcde , when I'm trying to get I'll have a cheese sandwich. 这将返回abcde ,当我尝试获取I'll have a cheese sandwich. In other words, the function is using the values from the list as the inputs, rather than using them as variables, which I define below. 换句话说,该函数将列表中的值用作输入,而不是将它们用作变量(我在下面定义)。 Of course, when I redefine: 当然,当我重新定义时:

def func(a,b,c,d,e):
    output = a+b+c+d+e
    return output

and define a through e I get the correct output. 并定义a通过e我得到正确的输出。

The code above is a gross oversimplification, but here's the goal: I am hoping to be able to remove d from my list (or add f to my list), and have it tell me I'll have a sandwich. 上面的代码过于简化,但这是我们的目标:我希望能够从列表中删除d (或在列表中添加f ),并告诉我I'll have a sandwich. (or I'll have a cheese sandwich, please. ) without having to redefine the function each time I need to handle a different number of variables. (或者I'll have a cheese sandwich, please. ),而不必在每次需要处理不同数量的变量时都重新定义函数。 Any thoughts are much appreciated. 任何想法都非常感谢。

args = (a, b, c, d, e) # not ('a', 'b', 'c', 'd', 'e')
func(*args)

Your code gets pretty close, but you seem to bee missing some key concepts. 您的代码非常接近,但是您似乎缺少一些关键概念。 When you create the varlist with the strings, they don't automatically refer to the objects you define below. 使用字符串创建varlist时,它们不会自动引用您在下面定义的对象。 You have to evaluate them. 您必须对其进行评估。 If you trust the source you can just use eval(), but if they user will input it, you might want to do something else. 如果您信任源,则可以只使用eval(),但是如果他们的用户将输入它,则可能需要执行其他操作。 Also, there is no need to unpack the list, just leave it as is. 同样,也无需拆开列表的包装,只需将其保持原样即可。 And don't name stuff in python the same name as builtins, in either version. 而且,无论哪个版本,都不要在python中使用与内建函数相同的名称命名。 Here is what I wrote with those changes. 这是我写的那些更改。

varlist = ('a','b','c','d','e')

def func(inp):
    output = ""
    for item in inp:
        output += item
    return output

a = "I'll "
b = "have "
c = "a "
d = "cheese "
e = "sandwich."

print func(map(eval, varlist))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM