Python:可变长度元组 [英] Python: variable-length tuples

查看:511
本文介绍了Python:可变长度元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[Python 3.1]

[Python 3.1]

我正在遵循元组应该具有已知长度的设计概念(请参阅

I'm following up on the design concept that tuples should be of known length (see this comment), and unknown length tuples should be replaced with lists in most circumstances. My question is under what circumstances should I deviate from that rule?

例如,我了解使用字符串和数字文字创建元组比使用列表更快(请参见

For example, I understand that tuples are faster to create from string and numeric literals than lists (see another comment). So, if I have performance-critical code where there are numerous calculations such as sumproduct(tuple1, tuple2), should I redefine them to work on lists despite a performance hit? (sumproduct((x, y, z), (a, b, c)) is defined as x * a + y * b + z * c, and its arguments have unspecified but equal lengths).

那么使用def f(*x)时Python自动构建的元组又如何呢?我认为这不是我每次使用时都应强制列出的内容.

And what about the tuple that is automatically built by Python when using def f(*x)? I assume it's not something I should coerce to list every time I use it.

顺便说一句,(x, y, z)的创建速度比[x, y, z]更快(对于变量而不是文字)?

Btw, is (x, y, z) faster to create than [x, y, z] (for variables rather than literals)?

推荐答案

在我看来,元组和列表之间唯一有趣的区别是列表是可变的,而元组则不是.人们提到的其他区别对我来说似乎完全是人为的:元组就像结构,而列表就像数组(这就是元组应该是已知长度"的来源).但是结构性如何与不变性保持一致?不是.

In my mind, the only interesting distinction between tuples and lists is that lists are mutable and tuples are not. The other distinctions that people mention seem completely artificial to me: tuples are like structs and lists are like arrays (this is where the "tuples should be a known length" comes from). But how is struct-ness aligned with immutability? It isn't.

唯一重要的区别是语言的区别:可变性.如果需要修改对象,请绝对使用列表.如果您需要对对象进行哈希处理(作为字典中的键或集合的元素),则需要使其不可变,因此请使用元组.就是这样.

The only distinction that matters is the distinction the language makes: mutability. If you need to modify the object, definitely use a list. If you need to hash the object (as a key in a dict, or an element of a set), then you need it to be immutable, so use a tuple. That's it.

这篇关于Python:可变长度元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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