type
status
date
slug
summary
tags
category
icon
password

引言:

在Python编程中,我们经常会使用到的两种基础数据结构就是列表(List)和元组(Tuple)。这两者都用于存储数据集合,但它们之间存在着一些关键的差异。理解这些差异以及何时使用哪种数据结构是成为一名高效的Python程序员的关键。在这篇博客中,我们将深入探讨列表和元组的主要特性和用途,并通过实例来更好地理解这些概念。

差异

我们已经有了列表这种数据结构,为什么还需要元组这样的类型呢?
列表(list)和元组(tuple)是Python中两种常用的序列数据类型。虽然它们在许多方面都很相似,但也有一些重要的差异:
  1. 不变性:列表是可变的,这意味着你可以改变一个列表的元素或长度。而元组是不可变的,一旦创建,就不能改变。
  1. 性能:由于元组是不可变的,所以它们通常比列表更加高效。如果你有一个不需要改变的序列,使用元组比使用列表更好。
  1. 安全性:元组的不变性使得它们可以作为字典的键,而列表不可以。此外,如果你要传递一个序列,并且不希望接收者改变这个序列,你应该使用元组。
  1. 语义:元组常常用于包含不同类型的元素,例如元组可能包含一个姓名和一个年龄。而列表通常用于包含多个相同类型的元素,例如一个整数列表或一个字符串列表。
  1. 内存使用:元组通常比列表占用更少的内存。因为元组是不可变的,Python在创建元组时可以更精确地分配内存,而列表由于其可变性,必须分配额外的内存来处理可能的增长,这导致列表占用的内存通常更多。
  1. 函数和方法:元组和列表都有一些内置的函数和方法,例如len()函数可以返回元组或列表的长度,append()方法(只适用于列表)可以在列表的末尾添加一个新元素,等等。
  1. 可哈希性:由于元组的不可变性,它们是可哈希的,这意味着你可以使用元组作为字典的键或将它们添加到集合中。而由于列表是可变的,它们不是可哈希的,所以你不能使用列表作为字典的键或将它们添加到集合中。

体现

不变性

python

# 列表是可变的 list_example = ['a', 'b', 'c'] list_example[1] = 'd' # 改变列表的一个元素 print(list_example) # 输出:['a', 'd', 'c'] # 元组是不可变的 tuple_example = ('a', 'b', 'c') try: tuple_example[1] = 'd' # 尝试改变元组的一个元素,会抛出异常 except TypeError: print('Cannot modify a tuple') # 输出:Cannot modify a tuple
Python

性能

元组的存储效率更高,创建和访问速度也更快。下面是一个使用Python的timeit模块比较列表和元组创建时间的例子:

python

import timeit print(timeit.timeit('x = (1,2,3,4,5,6)', number=1000000)) # 创建元组的时间 print(timeit.timeit('x = [1,2,3,4,5,6]', number=1000000)) # 创建列表的时间
Python

安全性

python

# 元组可以作为字典的键 dictionary = {('a', 'b'): 'c'} print(dictionary[('a', 'b')]) # 输出:'c' # 列表不能作为字典的键 try: dictionary = {['a', 'b']: 'c'} except TypeError: print('Cannot use a list as a dictionary key') # 输出:Cannot use a list as a dictionary key
Python

语义

python

# 元组包含不同类型的元素 person = ('Alice', 30) # 元组包含一个姓名和一个年龄 # 列表包含相同类型的元素 ages = [30, 35, 40] # 列表包含多个年龄
Python

内存使用

使用Python的sys模块来查看对象占用的内存大小:

python

import sys list_example = [1, 2, 3, 4, 5] tuple_example = (1, 2, 3, 4, 5) print(sys.getsizeof(list_example)) # 输出:96 print(sys.getsizeof(tuple_example)) # 输出:80
Python

函数和方法

python

list_example = [1, 2, 3, 4, 5] print(len(list_example)) # 输出:5 list_example.append(6) print(list_example) # 输出:[1, 2, 3, 4, 5, 6] tuple_example = (1, 2, 3, 4, 5) print(len(tuple_example)) # 输出:5 append()方法(只适用于列表)
Python

可哈希性

python

# 元组可以作为字典的键 dictionary = {(1, 2): 'a'} print(dictionary[(1, 2)]) # 输出:'a' # 列表不能作为字典的键 try: dictionary = {[1, 2]: 'a'} except TypeError: print('Cannot use a list as a dictionary key') # 输出:Cannot use a list as a dictionary key
Python

结语:

通过上述讨论和示例,我们了解了列表和元组的关键区别,包括其可变性、性能、内存使用、嵌套和可哈希性等特性。尽管列表和元组在很多方面都很相似,但是这些差异使得它们在特定的应用场景中具有各自的优势。在编写Python代码时,应根据实际需求选择使用列表还是元组。
最后的最后: 人生苦短 我用python ^_^

python

>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
Python
排序算法探究探索pyhon的面向对象编程
宓翊23
宓翊23
博学而笃志,切问而近思~ 爱探索,热爱技术的Geek一枚~
Announcement
type
status
date
slug
summary
tags
category
icon
password
🎉欢迎来到我的博客🎉
工具-资源-技术-随笔
--- 感谢您的支持 ---
👏希望能帮助到您👏
主博客:作者站点中的bevis23
 
 
 
2024-2025 宓翊23.

miyi23 | 博学而笃志,切问而近思~ 爱探索,热爱技术的Geek一枚~

Powered by NotionNext 4.1.5.