同时声明多个变量的更优雅的方式 [英] More elegant way of declaring multiple variables at the same time

查看:98
本文介绍了同时声明多个变量的更优雅的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在相同时间声明多个变量,我应该这样做:

To declare multiple variables at the "same time" I would do:

a, b = True, False

但是如果我不得不声明更多的变量,它的优雅程度就会越来越小:

But if I had to declare much more variables, it turns less and less elegant:

a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True ,True , True, True

是否有更好/优雅/便捷的方法?

Is there a better / elegant / convenient way to do this?

这必须是非常基本的,但是如果我确实使用列表或元组来存储变量,那么我将不得不采用哪种方法,这样对我有帮助,因为: / p>

This must be very basic, but if I do used a list or a tuple for storing the variables, how would I have to approach so that I would be helpful since:

aList = [a,b]

无效,我必须这样做:

a, b = True, True

或者我想念什么?

推荐答案

正如其他人所建议的那样,将10个不同的局部变量与布尔值一起使用不太可能是编写例程的最佳方法(特别是ly,如果他们确实有一个字母的名字:)

As others have suggested, it's unlikely that using 10 different local variables with Boolean values is the best way to write your routine (especially if they really have one-letter names :)

根据您在做什么,可以改用词典。例如,如果要为一组单字母标志设置布尔值预设值,则可以执行以下操作:

Depending on what you're doing, it may make sense to use a dictionary instead. For example, if you want to set up Boolean preset values for a set of one-letter flags, you could do this:

>>> flags = dict.fromkeys(["a", "b", "c"], True)
>>> flags.update(dict.fromkeys(["d", "e"], False))
>>> print flags
{'a': True, 'c': True, 'b': True, 'e': False, 'd': False}






如果愿意,也可以使用单个赋值语句来完成此操作:


If you prefer, you can also do it with a single assignment statement:

>>> flags = dict(dict.fromkeys(["a", "b", "c"], True),
...              **dict.fromkeys(["d", "e"], False))
>>> print flags
{'a': True, 'c': True, 'b': True, 'e': False, 'd': False}

dict 的第二个参数并非完全为此目的而设计的:它的真正含义是允许您覆盖使用诸如 d = False 之类的关键字参数的字典中的各个元素。上面的代码将 ** 之后的表达式的结果分解为一组关键字参数,该参数将传递给调用的函数。当然,这是创建字典的可靠方法,人们似乎至少接受了这种习语,但我怀疑有人可能认为它是非Python的。 < /免责声明>

The second parameter to dict isn't entirely designed for this: it's really meant to allow you to override individual elements of the dictionary using keyword arguments like d=False. The code above blows up the result of the expression following ** into a set of keyword arguments which are passed to the called function. This is certainly a reliable way to create dictionaries, and people seem to be at least accepting of this idiom, but I suspect that some may consider it Unpythonic. </disclaimer>

另一种方法是如果您将经常使用此模式,则最直观的方法可能是将数据定义为标志值列表( True False )映射到标志名称(单字符字符串)。然后,您可以将此数据定义转换为反向字典,该字典将标志名称映射到标志值。使用嵌套列表理解可以很简洁地完成此操作,但这是一个非常易读的实现:

Yet another approach, which is likely the most intuitive if you will be using this pattern frequently, is to define your data as a list of flag values (True, False) mapped to flag names (single-character strings). You then transform this data definition into an inverted dictionary which maps flag names to flag values. This can be done quite succinctly with a nested list comprehension, but here's a very readable implementation:

>>> def invert_dict(inverted_dict):
...     elements = inverted_dict.iteritems()
...     for flag_value, flag_names in elements:
...         for flag_name in flag_names:
...             yield flag_name, flag_value
... 
>>> flags = {True: ["a", "b", "c"], False: ["d", "e"]}
>>> flags = dict(invert_dict(flags))
>>> print flags
{'a': True, 'c': True, 'b': True, 'e': False, 'd': False}

函数 invert_dict 发电机功能。它 generates yields —意味着它反复返回 —键值对的值。这些键值对与初始 flags 字典中两个元素的内容相反。它们被馈入 dict 构造函数。在这种情况下, dict 构造函数的工作原理与上面有所不同,因为正在为其提供迭代器,而不是字典作为其参数。

The function invert_dict is a generator function. It generates, or yields — meaning that it repeatedly returns values of — key-value pairs. Those key-value pairs are the inverse of the contents of the two elements of the initial flags dictionary. They are fed into the dict constructor. In this case the dict constructor works differently from above because it's being fed an iterator rather than a dictionary as its argument.

借鉴@Chris Lutz的评论:如果您真的将它用于单个字符值,则可以实际使用

Drawing on @Chris Lutz's comment: If you will really be using this for single-character values, you can actually do

>>> flags = {True: 'abc', False: 'de'}
>>> flags = dict(invert_dict(flags))
>>> print flags
{'a': True, 'c': True, 'b': True, 'e': False, 'd': False}

这有效,因为Python字符串为 iterable ,表示它们可以逐个值地移动。对于字符串,值是字符串中的各个字符。因此,当它们被解释为可迭代时,例如在for循环中使用它们的情况下, ['a','b','c'] 'abc'是等效的。另一个示例是将它们传递给需要迭代的函数时,例如 tuple

This works because Python strings are iterable, meaning that they can be moved through value by value. In the case of a string, the values are the individual characters in the string. So when they are being interpreted as iterables, as in this case where they are being used in a for loop, ['a', 'b', 'c'] and 'abc' are effectively equivalent. Another example would be when they are being passed to a function that takes an iterable, like tuple.

我个人不会这样做,因为它不会直观地显示:当我看到一个字符串,我希望它可以用作单个值而不是列表。所以我看第一行,然后想:好吧,所以有一个True标志和一个False标志。因此,尽管有可能,但我认为这不是可行的方法。从好的方面来说,这可能有助于更清楚地解释迭代器和迭代器的概念。

I personally wouldn't do this because it doesn't read intuitively: when I see a string, I expect it to be used as a single value rather than as a list. So I look at the first line and think "Okay, so there's a True flag and a False flag." So although it's a possibility, I don't think it's the way to go. On the upside, it may help to explain the concepts of iterables and iterators more clearly.

定义函数 invert_dict 使得它实际上返回一个字典也不是坏主意;我大多只是不这样做,因为它并不能真正帮助解释例程的工作原理。

Defining the function invert_dict such that it actually returns a dictionary is not a bad idea either; I mostly just didn't do that because it doesn't really help to explain how the routine works.

显然是Python 2.7具有字典理解功能,这将为实现该功能提供极为简洁的方法。这留给读者练习,因为我没有安装Python 2.7:)

Apparently Python 2.7 has dictionary comprehensions, which would make for an extremely concise way to implement that function. This is left as an exercise to the reader, since I don't have Python 2.7 installed :)

您还可以组合来自多功能的 itertools 模块。就像他们说的那样,有多种方法可以实现。等等,Python人士不会这么说。嗯,在某些情况下还是如此。我猜想Guido给了我们字典理解,所以会有一种明显的方法为此。

You can also combine some functions from the ever-versatile itertools module. As they say, There's More Than One Way To Do It. Wait, the Python people don't say that. Well, it's true anyway in some cases. I would guess that Guido hath given unto us dictionary comprehensions so that there would be One Obvious Way to do this.

这篇关于同时声明多个变量的更优雅的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆