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

4.10 Python tuples

編輯:Python

4.10 Tuples

Python Data type No 1 Kind of : character string (str), What is enclosed in quotation marks .
Python Data type No 2 Kind of : Integers (int).
Python Data type No 3 Kind of : Floating point numbers (float), A number with a decimal point .
Python Data type No 4 Kind of : list (list), In square brackets [ ] Express .
Python Data type No 5 Kind of : Tuples (tuple), Use parentheses ( ) Express .

4.10.1 The concept of tuples

Tuples, like lists, are data structures used to store a set of ordered data .
Tuple use ( ) Express , The elements are separated by commas .
Lists are variable data types , Tuples are immutable data types .
Immutability means that you cannot add elements to tuples , Or modify the elements of tuples .

4.10.2 Create a new tuple

# Create a new tuple 
tup = (' Zhang San ',30,' Li Si ',40 )
# Look at tuples 
tup

【 Terminal output 】
(‘ Zhang San ’, 30, ‘ Li Si ’, 40)

Be careful : list 、 The parentheses of tuples and commas between elements are input in English .

4.10.3 len( ) Function to view the tuple length

# Create a new tuple 
tup = (' Zhang San ',30,' Li Si ',40 )
# Check the tuple length 
len(tup)

【 Terminal output 】
4

Terminal output 4, Indicates that the tuple has 4 Elements .

4.10.4 Index view tuple elements

# Create a new tuple 
tup = (' Zhang San ',30,' Li Si ',40 )
# View tuple number 3 Elements 
tup[2]

【 Terminal output 】
‘ Li Si ’

For viewing elements Tuples .[ Indexes ] Methods .
The first 3 Elements , The index for [2].

4.10.4 Conversion between list and tuple

Tuples into lists

grammar :list( Tuples )

# Create a new tuple 
tup = (' Zhang San ',30,' Li Si ',40 )
# Converts a tuple to a list 
list(tup)

【 Terminal output 】
[‘ Zhang San ’, 30, ‘ Li Si ’, 40]

List to tuple

grammar :tuple( list )

# Create a new list 
list_1 = [' Zhang San ', 30, ' Li Si ', 40]
# Converts a tuple to a list 
tuple(list_1)

【 Terminal output 】
(‘ Zhang San ’, 30, ‘ Li Si ’, 40)

4.10.5 Tuples with only one element

If the tuple has only one element , That element also needs to be followed by an English comma , .

# Create a new tuple with only one element 
name_tup = (' Bai Jingting ',)
# Look at tuples 
print(name_tup)
# View data type 
type(name_tup)

【 Terminal output 】
(‘ Bai Jingting ’,)
tuple

# Suppose there is no comma 
name_tup = (' Bai Jingting ')
# Check the variable 
print(name_tup)
# View data type 
type(name_tup)

【 Terminal output 】
Bai Jingting
str

Through the above code discovery , There are English commas in tuples , What doesn't have an English comma is a string .


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