列表应该总是转换为元组吗? [英] Should lists always be converted to tuples?
问题描述
我正在努力加强我的最佳实践",我正在阅读有关列表与元组和内存分配的更多信息,以及如果列表不会随着程序运行而更改,您应该如何使用元组.
话虽如此,如果是这种情况,您(几乎)是否应该总是从列表转换为元组?
例如,假设我有这个代码,我正在查看用户输入的 100 种颜色:
with open("colors.txt", "r") 作为文件:lst = [line.strip() for line in file.readlines()]
我不打算改变列表.这是否意味着我应该遵循:
tup = tuple(lst)
然后解决tup
?
我意识到这是一个很小的例子,转换为元组只需要 1 行,但这是最佳实践吗?只是感觉有点笨重,因为它对我来说是新的.
谢谢!
我想我会按照 OP 的要求回答.
首先,最佳实践"在您不打算修改集合的情况下,通常意味着使用 tuple
,是的.你可以跳过笨拙"通过简单地避免首先创建 list
来进行转换:
with open("colors.txt", "r") as f:颜色 = 元组(地图(str.strip,f))
<块引用>
归功于@khelwood
或
tuple(some_expression for item in some_iterable)
对于更复杂的表达式.
正如@snakecharmerb 指出的那样,当元素的顺序很重要时,使用 tuple
也是一个好主意.由于 tuple
对象是不可变的,元素在 tuple
中的放置顺序是一成不变的".如果你愿意.这向读者表明顺序对您的数据极为重要.
对于顺序不重要并且您想要强制执行唯一元素的时候,set
是理想的,因为它们仍然是可迭代的,而且还有 恒定时间 成员资格检查,这在某些情况下可能会有所帮助.
I'm trying to beef up my "best practices," and I'm reading more about lists vs. tuples and memory allocation, and how you should use tuples if the list is not going to be changed as the program runs.
That being said, should you (almost) always convert from a list into a tuple if this is the case?
For example, let's say I have this code, and I'm looking at 100 colors input from users:
with open("colors.txt", "r") as file:
lst = [line.strip() for line in file.readlines()]
I'm not planning on mutating the list. Does that mean I should follow with:
tup = tuple(lst)
and work off of tup
?
I realize this is a pretty small example, and converting to a tuple only takes 1 line, but is this the best practice? It just feels a little clunky since it's new to me.
Thanks!
I suppose I'll answer, as requested by OP.
First, "best practice" in cases where you do not plan to modify a collection generally means using a tuple
, yes. You can skip the "clunkiness" of casting by simply avoiding creating a list
in the first place:
with open("colors.txt", "r") as f:
colors = tuple(map(str.strip, f))
credit to @khelwood
Or
tuple(some_expression for item in some_iterable)
For more complicated expressions.
As @snakecharmerb points out, using a tuple
is also a good idea when the order of your elements is important. Since tuple
objects are immutable, the order in which elements are placed in the tuple
are "set in stone" if you will. This signifies to the reader that order is extremely important for your data.
For times when order is NOT important and you want to enforce unique elements, a set
is ideal as they are still iterable but also have constant time membership checking, which can be helpful in some situations.
这篇关于列表应该总是转换为元组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!