简体   繁体   English

在函数参数中列出理解

[英]List comprehension in function arguments

In Python 2.7.1, I'm trying to provide a list of messages as the first argument, and a list of colors as the second argument. 在Python 2.7.1中,我试图提供一个消息列表作为第一个参数,并将颜色列表作为第二个参数。 I want the second argument to default to a list of whites if it's not provided. 我希望第二个参数默认为白色列表,如果没有提供的话。 This is the way I tried to do it: 这是我试图这样做的方式:

def multicolor_message(msgs, colors=[libtcod.white for x in len(msgs)]):
#function body

libtcod.white is a part of the library I'm using and is in no way causing any problems. libtcod.white是我正在使用的库的一部分,并且不会导致任何问题。 The compiler says the variable msgs is not defined. 编译器说没有定义变量msgs Obviously the msgs variable doesn't exist in this scope, but I need to create a list of appropriate length and assign it to colors . 显然, msgs变量在此范围内不存在,但我需要创建一个适当长度的列表并将其分配给colors What is the cleanest way to do this? 最干净的方法是什么?

I would do it like this: 我会这样做:

def multicolor_message(msgs, colors=None):
  if colors is None:
    colors=[libtcod.white for x in len(msgs)]

That's not possible is python, as function's default arguments are executed at function definition time and your msgs variable will not be available until the function is called. 这是不可能的python,因为函数的默认参数在函数定义时执行,并且在调用函数之前, msgs变量将不可用。

From the docs : 来自文档

Default parameter values are evaluated when the function definition is executed. 执行函数定义时,将评估默认参数值。 This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. 这意味着当定义函数时,表达式被计算一次,并且每次调用使用相同的“预先计算”值。 This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (eg by appending an item to a list), the default value is in effect modified. 这对于理解默认参数是可变对象(例如列表或字典)时尤其重要:如果函数修改对象(例如,通过将项附加到列表),则默认值实际上被修改。 This is generally not what was intended. 这通常不是预期的。 A way around this is to use None as the default, and explicitly test for it in the body of the function, eg: 解决这个问题的方法是使用None作为默认值,并在函数体中显式测试它,例如:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

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

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