将序列常数写成元组的最佳实践?并在测试包含时设置?
如果我们的代码中有较小的序列常数,那么将它们写成元组而不是列表是最好的做法吗?还是真的没关系?
例如order_types =(1,2,3)
vs order_types = [1,2,3]
,当我们打算使用包含操作对该顺序使用纳入操作时,这是有道理的存储作为一套?
例如
ORDER_TYPES = {1, 2, 3}
order_type = 1
if order_type in ORDER_TYPES:
...
,当序列很小时,作为元组与列表的存储有任何实际的速度/空间优势,或者是一组?我知道这属于过度优化的领域,但只是想知道什么实际上被认为是最佳实践。
If we have small sequence constants in our code, is it best practice to write them as tuple rather than as a list? Or does it not really matter?
e.g. ORDER_TYPES = (1, 2, 3)
vs ORDER_TYPES = [1, 2, 3]
And when we intend to use inclusion operations against that sequence, does it make sense to store as a set?
e.g.
ORDER_TYPES = {1, 2, 3}
order_type = 1
if order_type in ORDER_TYPES:
...
Are there any actual speed/space benefits to storing as tuple vs list, or as a set, when the sequences are small like this? I know this falls into the realm of over-optimizing but just wondering what is actually considered best practice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
建议使用元组,
实际上,在您的情况下,没有太多差异,因为它们不是太多,并且没有经常使用。
但是,当您提到问题中的最佳练习时,尽管您可以(允许)使用任何数据结构会EV字符串,但是您的问题与一般最佳实践案例之间没有区别。
因此,请仔细观察此链接或其他类似的链接。
另外,在这里 提供了更多详细信息。
Using tuples is recommended,
Actually in your case there not much difference as they are not too many and they are not being used a lot.
but when you mentioned best practice in your question although you can(allowed) to use any data structure evens strings but there is no difference between your question and general best practice cases.
so take a close look at This link or other similar links.
Also Here explains with more details.
列表和集合之间的主要区别是效率主要在中的
之类的操作中。例如:
在这种情况下,使用集合比列表要高得多,因为集合在低级别上与哈希地图一起使用,因此它具有
o(1)
时间复杂性,用于检查元素是否元素包含在一组中。同时,列表和元组采取o(n)
复杂性,这要贵得多。另外,使用
set
允许您在o(1)
复杂性中插入元素。您可以使用此 resource。
The main difference between lists and sets are the efficiency mainly in operations like
in
. For example:In this case, using a set is much more efficient than a list because sets work with hash maps on the low level, so it will have
O(1)
time complexity for checking if an element is contained in a set. Meanwhile, lists and tuples takeO(n)
complexity, which is much more expensive.Also, using
set
allows you to insert elements inO(1)
complexity too.You can learn more about both structures with this resource.