程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How does Python modify tuples? How to modify tuples?

編輯:Python

One 、 Knowledge that everyone knows

Tuples (tuple) It can't be modified , This is also the biggest difference between it and the list .

Two 、 How to modify tuples ?

Since tuples cannot be modified , So why do we mention modifying tuples here ? In fact, we are talking about pseudo modification , That's all “ After modification ” Created a new metagroup , The address of the original tuple is different from that of the new tuple .

“ modify ” Method 1 : Using modifiable objects as mediators

utilize list function ( or set function 、numpy.array function ...) Convert to list ( Or set 、 Array and other modifiable objects ) We'll change it later .

“ modify ” Method 2 : Reassign a new tuple .

e = (1, 2)
f = (3, 4)
print(id(e)) # 2518329767872
print(id(f)) # 2517956197824

Be careful , Even if the assignment is the same , The addresses of two tuples are also different .( list 、 The same is true of containers such as dictionaries )

e = (1, 2)
f = (1, 2)
print(id(e)) # 2518329741824
print(id(f)) # 2518329767872

But for string variables 、 Numerical variable , Assign the same string 、 The number , The two variables are actually the same .

g = 'bguryeidbauisfbsigvb'
h = 'bguryeidbauisfbsigvb'
print(id(g)) # 2518329751952
print(id(h)) # 2518329751952

Modify method 3 : utilize 【+】 To add tuple elements

As you can see from the code , Tuples added h Tuples of elements in j And tuples g Is not the same , Because the address is different .

g = (1,2)
h = (1,2,3)
j = g + h
print(g) # (1,2)
print(h) # (1,2,3)
print(j) # (1,2,1,2,3)
print(id(g)) # 2518329751952
print(id(h)) # 2518329767232
print(id(j)) # 2517955499968

Be careful : Add elements to a tuple , Can't use append; But the list 、 Dictionaries 、 Array 、 It is possible to change containers such as collections !

g = (1,2)
g.append(3) # AttributeError: 'tuple' object has no attribute 'append'
h = [1,2,3]
h.append(4)
print(h) # [1,2,3,4]


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved