当前位置:网站首页>tuple and point

tuple and point

2022-07-05 02:24:00 Incoming brother

Tuples

About tuples : Tuples are in Python of use () Express , Unlike lists, tuples cannot be modified

If the tuple has only one value , We can't just write a value , This will turn Python The interpreter is confused

We're going to write ( value ,) Form like this

The purpose of tuples is to tell people who read code , You don't want to change this thing

hello = [1,2,3]
hello[1] = 4
# Wrong writing 

tuple() and list()

We can convert tuple type to list type , You can also convert a list type to a tuple type

a = tuple([1,2,4])
print(type(a))
#  Output is tuple type 
a = list((1,2,3,4))
print(tupe(a))
#  Output is list type 

About quoting

Before you know about references , Let's compare the two programs first

a = 1
b = a
b = 2
print(a) #1
print(b) #2

We found this a The value of

a = [1,2,3]
b = a
b[0] = 0
print(a) # [0,2,3]
print(b) # [0,2,3]

We found out here a[1] The value of has changed , Mainly because of a It's a reference ,a Point to the list

b = a, It means to make b Also points to the list

Pass on references

def add(p):
    a.append(4)

a = [1,2,3]
add(p)
print(a)
# [1,2,3,4]

This happens to lists and dictionaries

If you don't want this quote to happen , You can use full assignment

import copy
a = [1,2,3,4]
b = copy.copy(a)
b[1] = 0
print(a) #[1,2,3,4]
print(b) #[0,2,3,4]
print('========')
#  If a list is nested in the list 
c = [1,[1,2,3]]
d = copy.deepcopy(c)
d[1] = 0
print(c)
print(d)

summary :

1). The list is variable , Tuples are immutable
2). The assignment of a list is a reference
3). The complete assignment is copy.copy(list),copy.deepcopy(list)

原网站

版权声明
本文为[Incoming brother]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140926555395.html