我是一名 Perl 专家,目前正在学习 Python。如果我在 Perl 中有一个列表,我可以将它的值(成员)分配给显式变量,如下所示:
my ($a, $b, $c) = ('one', 'two', 'three');
现在 $a == 'one',$b == 'two',$c == 'three'。与 Python 非常相似。
如果我对例如第二个成员,我可以用 Perl 写这个:
my ($a, undef, $c) = ('one', 'two', 'three');
现在 $a == 'one' 和 $c == 'three'。没有$b。 'two' 被 Perl 简单地丢弃了。这避免了发明无用的变量(在本例中为 $b)和污染命名空间,这点我很感激。
Python 中有类似的习语吗?
toople = (1, 2, 3)
a, None, c = toople
给出 SyntaxError: cannot assign to None 这对我来说听起来很合理。
有没有办法在 Python 中避免使用(无用的)变量 b?
除了 namespace 污染,还有一个问题让我很担心:可读性和可维护性。当定义了 b 时,潜在的维护者必须搜索在哪里使用了 b(如果有的话)。一种解决方案是命名约定,例如 _unused_b。这是解决方案吗?
请您参考如下方法:
由于您是按位置选择的,所以要么采用特定元素
a, c = [ toople[i] for i in [0,2] ]
或者排除其他的
a, c = [ item for i, item in enumerate(toople) if i not in [1] ]
这些使用list comprehension和 enumerate
一种让人联想到 Perl 的 undef 的方法是使用 _ 作为一次性变量,但正如评论中指出的那样,这与 _ 的国际化冲突可能正在使用中。参见 answers in this post .
