Use tuples: Python

"""
元组:把多个元素组合在一起就是元组,与列表类似
    最常见的元组就是坐标
"""
# 定义元组
t = ('fqx', '男', 22, True)
print(t)  # ('fqx', '男', 22, True)

# 获取元组中的元素
print(t[0])  # fqx
print(t[3])  # True

# 遍历元组的值
for i in t:
    print(i, end=' ')  # fqx 男 22 True
print()
# 重新给元组赋值
# t[0] = '王大锤'
# print(t)  # TypeError: 'tuple' object does not support item assignment(元组只能读,不能写)

# 真想修改怎么办?
t = ('王大锤', '男', 22, True)
print(t)  # ('王大锤', '男', 22, True)
# 在这里变量t重新引用了新的元组原来元组将被垃圾回收

# 将元组转换为列表
person = list(t)
print(person)  # ['王大锤', '男', 22, True]

# 列表可以修改元素的
person[0] = '王小锤子'
print(person)  # ['王小锤子', '男', 22, True]

# 将列表转换为元组
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)  # ('apple', 'banana', 'orange')


# 比较列表和元组所占内存
import sys
print(sys.getsizeof(fruits_list))  # 80
print(sys.getsizeof(fruits_tuple))  # 64


Why use a tuple?


1. tuple space created above takes time and is superior to the list.
  We can use the sys module getsizeof function to check:
  tuples and lists the same respective elements stored how much memory space


2. tuple elements can not be modified
    in fact, we especially multi-threaded environment may prefer to use are those same objects in the project
    (on the one hand because of the state of the object can not be modified, avoid unnecessary procedural errors,
    simply put, is a constant than a variable target object easier to maintain;
    on the other hand because no one thread can modify the internal state of the same object,
    a constant objects are automatically thread-safe, so you can save processing overhead out of sync.
    a constant object can be easily shared access).
    So the conclusion is this:
    If the elements do not need to add, delete, modify, they can consider using tuples,
    of course, if a method to return multiple values, use a tuple is a good choice.

 

Published 52 original articles · won praise 34 · views 2618

Guess you like

Origin blog.csdn.net/weixin_38114487/article/details/103871729