Detailed introduction to Python data types

1. Number

1. int (integer, long integer)

2. float (floating point type)

3. complex (plural)

2. Boolean

3. String type (String)

 4. List

1. Create a list

2. Index of the list

 3. Slicing of lists

4. List addition and multiplication

5. Modification of list

6. Deletion of list

7. List appending, inserting and expanding

8. Searching for list elements

9. Related built-in functions related to lists

10. Multidimensional list

Quintuple

1. Overview of tuples

2. Tuple modification

 3. Tuple deletion

4. Built-in functions related to tuples

5. Conversion between tuples and lists 

6. Advantages of tuples

6. Dictionary

1. Creation of dictionary    

2. Dictionary access

3. Modification of dictionary

4. Delete dictionary

5. Addition of dictionary

6. Built-in functions related to dictionaries

 7. Collection

1. Creation of collections

2. Characteristics of collections

3. Add elements to the collection

4. Delete elements from a collection

5. Numerical operations on sets

6. frozenset in collections


Python has seven major data types:

(1) Number: int (integer, long integer), float (floating point), complex (plural number)

(2) Boolean: True, False

(3) String: "Python", 'python'

(4) List: [1,2,3,4], [1,2,3,[1,2,3],"hello"]

(5)字典(Dictionary):{1:"hello",2:"world"}

(6) Tuple: (1,2,3, "hello", "world")

(7) Set: {1,2,3, "hello"}

Note: It is also said that Python has six major data types, among which Boolean is placed in the numeric type.

There are 4 immutable types: numbers, Boolean, strings, and tuples

There are three variable types: list, dictionary, and set.

 A mutable data type means that the content can change as the function executes.

Immutable data types are unchangeable from initialization to completion.

Let’s take a closer look at each type below

1. Number

1. int (integer, long integer)

  • In python, integers and long integers are combined. In python3, there is only int, but there is no long int or long long int.
  • You can use the maxsize of the sys module to obtain the maximum integer supported by the system.
import sys
print(sys.maxsize)

输出结果为:
9223372036854775807

2. float (floating point type)

  • Floating point numbers can be represented in decimal point form,
  • It can also be expressed in the form of science and technology law (e or E can be used)

For example: m = 3e2 (3e2 represents 3 times 10 raised to the power 2), at this time m = 300

         n = 3E2 (E and e have the same meaning, both represent the power of 10), at this time n = 300

f = 0.01
m = 5e3
n = 5E3
print('f=',f,'m=',m,'n=',n)

输出的结果为:
f= 0.01 m= 5000.0 n= 5000.0

3. complex (plural)

  • A complex number consists of a real part and an imaginary part. It is often represented by a+bj or complex(a,b) in Python, where a represents the real part of the complex number, b represents the imaginary part of the complex number, and the real part a and the imaginary part of the complex number b are all floating point types
  • Use the real function to get the real part value, and use imag to get the imaginary part value.
  • Use conjuate() to find the conjugate complex number of a complex number (the conjugate complex number means that the real part is the same and the sign of the imaginary part is opposite)
c = 10 + 20j
d = complex(5, 10)
# c.real 实部  c.imag 虚部  c.conjugate 共轭复数
print(c, d,  c.real, c.imag, c.conjugate())

输出的结果如下:
(10+20j) (5+10j) 10.0 20.0 (10-20j)

2. Boolean

  • The Boolean type is a data type that has only two values: True and False ( note that the first letter of the word must be capitalized ).
  • Commonly used Boolean operations include and, or, and not. Boolean type values ​​can be added, but once added, the type will be converted to int type.

    Operation

    result

    x and y

    The result is True only when x and y are True at the same time.

    x or y

    As long as one of x and y is True, the result is True

    not x

    Negation, that is, when x is True, the result is False

    a = True
    b = False
    print(a and b)
    print(a or b)
    print(not a)
    print(a+b)    # 当两个布尔型进行算数运算时就会转换成int类型
    
    输出结果如下:
    False
    True
    False
    1

3. String type (String)

  •  The String type is a well-known type. When defining a string value, you can use single quotes or double quotes.

a = 'hello'
b = "world"
print(a,b)

输出结果为:
hello world

 4. List

1. Create a list

  • Variable name = [element 1, element 2, element 3,..., element n]
  • The data in the list are called elements of the list, and the elements are separated by commas
  • There can be multiple data types in the same list
  • Elements in the list can be repeated

For example:

list1 = [1,2,3,4] where 1,2,3,4 are the elements of the list

list2 = [1,2,3,'hello',12] There can be multiple data types in the same list

list3 = [1,2,3,4,1,2,3] elements in the list can be repeated

2. Index of the list

  • Each element of the list corresponds to an integer index value, and the corresponding element value can be obtained through the index value.
  •   Lists support forward and reverse indexing of elements. Forward index means that the index value is positive and starts from 0; reverse index means that the index value is negative and starts from -1. If it is a reverse index, -1 is the index number corresponding to the last element.
  • It should be noted here that the forward index value is positive and starts from 0, and the reverse index value is negative and starts from -1
list1 = [1,2,3,4,'hello']
print("列表list1的第一个值:",list1[0])
print("列表list1的最后一个值:",list1[-1])

输出结果如下:
列表list1的第一个值: 1
列表list1的最后一个值: hello

 3. Slicing of lists

  • List slicing refers to intercepting sub-elements in the list and regenerating the intercepted elements into a sub-list.

  • Slicing is done from left to right

  • The format is: new list = old list [start value: end value]   (It should be noted that the slice position here is left closed and right open , which means that the generated new list contains the element corresponding to the starting index, but does not include The element corresponding to the termination index)]

list1 = [1,2,3,4,5,6,7,8,9]
list2 = list1[2:6]
# 2表示起始索引值为2,此处对应的元素值为3
# 6表示终止索引值为6,此处对应的元素值为7
list3 = list1[-6:-3]
print('list2=',list2)
print('list2=',list3)

输出结果为:
list2= [3, 4, 5, 6]
list2= [4, 5, 6]

4. List addition and multiplication

  • The addition operation is completed using the plus sign (+), which means that the list variables at both ends of the plus sign are connected to form a new list.
  • The multiplication operation is completed using an asterisk (*), which means that the current list object is copied and connected to form a new list
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1+list2
list4 = list1*3
print("list3=",list3)
print("list4=",list4)

输出结果如下:
list3= [1, 2, 3, 4, 5, 6]
list4= [1, 2, 3, 1, 2, 3, 1, 2, 3]

5. Modification of list

  • Modify by index of list
  • Modify by slice of list
list1 = [1,2,0,4,5,6,7]
# 将索引值为2的元素的值修改为三
list1[2] = 3
print(list1)
list1[2:6]=[0,0,0,0]
print(list1)

输出结果为:
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 0, 0, 0, 0, 7]

6. Deletion of list

There are four methods for list deletion: del, pop, remove, clear

  • del: keyword, forced deletion, you can only delete the value corresponding to a certain index in the list, or you can directly delete the entire list
  • pop: If the deletion position is not specified, the last one will be deleted by default.
  • remove: Delete the specified value (only delete the element that is matched for the first time). If there is no match, an error will be reported.
  • clear: clear the list, just delete the elements in the list, but the list is still there
list1 = [1,2,1,4,5,6,7]
# 删除列表索引为1的值
del list1[1]
print("list1=",list1)   #list2= [1, 1, 4, 5, 6]

list2= [1,2,1,4,5,6,7]
#默认删除列表中的最后一个值
list2.pop()
# 删除列表索引为1的值
list2.pop(1)
print("list2=",list2)  #list1= [1, 1, 4, 5, 6, 7]
list3 = [1,2,1,4,5,6,7]
# s删除列表中值为1的元素,如果列表中有多个,则默认删除第一个
list3.remove(1)
print("list3=",list3)   #list3= [2, 1, 4, 5, 6, 7]

list4 = [1,2,1,4,5,6,7]   
# 请款列表
list4.clear()
print("list4=",list4)   #list4= []

7. List appending, inserting and expanding

  •  append: append elements to the end of the current list object  
  •  insert: Insert an element at the specified index position in the current list    
  • extend: Add batches to the current list elements
list1 = [1,2,3,4,5,6,7]
list1.append(8)
list1.append([9,10])
print("list1 =",list1)
对应输出结果为:list1 = [1, 2, 3, 4, 5, 6, 7, 8, [9, 10]]

list2 = [1,2,4,5,6,7]
#在列表索引值为2的,增加元素3
list2.insert(2,3)
print("list2 =",list2)
对应输出结果为:list2 = [1, 2, 3, 4, 5, 6, 7]

list3 = [1,2,3]
list3.extend([4,5,6])
print("list3 =",list3)
对应输出结果为:list3 = [1, 2, 3, 4, 5, 6]

8. Searching for list elements

  •  List uses the index function to find the corresponding element and returns the index of the element. obj is the element value, start and end are the start and end indexes (both optional), and an error is reported if the element does not exist.
  • The format is: list.index(obj,start,end) If it cannot be found, an error will be reported. 
list1 = [1,2,3,4,5,6]
print(list1.index(4,1,5))   # 查找到了索引位置为3
print(list1.index(5))        # 查找到了索引位置为4

9. Related built-in functions related to lists

list function

function

meaning

len(list)

Number of list elements

max(list)

Returns the maximum value of a list element

min(list)

Returns the minimum value of a list element

list(seq)

Convert sequence to list

len(list)

Number of list elements

max(list)

Returns the maximum value of a list element

min(list)

Returns the minimum value of a list element

list(seq)

Convert sequence to list

10. Multidimensional list

A multidimensional list means that the elements of the list are also lists, similar to a multidimensional array

list1 = [1,2]
list2 = [1,2,3]
list3= [list1,list2]
print(list3)
输出如下:
[[1, 2], [1, 2, 3]]    
# list3 是二维列表

Quintuple

1. Overview of tuples

  •  Tuple is an immutable data type that can contain multiple data types . It is the only immutable composite data type in Python.
  •  Creation of Tuple variable name = (element 1, element 2,..., element n)

  • Tuples are recognized from the form of lists, and are marked by "(" parentheses. When there is only one element in the tuple, a comma needs to be added after the element. Tuples are also accessed through indexes, and slicing operations are supported.

2. Tuple modification

Tuples are immutable data types, so they cannot be modified, but they can be reassigned and connected with "+" to generate new tuples.

# 元组可以包涵多种数据类型
tup1 = (1,2,3,4,'hello')
# 当元组只有一个元素时,需要在元素后面加一个逗号
tup2 = ("world",)
# 给元组进行+ 运算,从新生成一个新的元组
tup3 = tup1 + tup2
print(tup3)


输出结果为:
(1, 2, 3, 4, 'hello', 'world')

 3. Tuple deletion

Element values ​​are not allowed to be deleted , but the entire tuple can be deleted using the del statement  . It should be noted that the deleted tuple object cannot be referenced again.

tup1 = (1,2,3,4,'hello')
del tup1
print(tup1)

#用del 将元组删除之后是不能在对之前的元组进行引用的,否则会报错
Traceback (most recent call last):
  File "F:\course_study\python3\test\training\Type.py", line 89, in <module>
    print(tup1)
NameError: name 'tup1' is not defined

4. Built-in functions related to tuples

tuple function

function

meaning

cmp(tuple1, tuple2)

Comparing two tuple elements is no longer available in Python 3

len(tuple)

Count the number of tuple elements

max(tuple)

Returns the maximum value of the elements in the tuple

min(tuple)

Returns the minimum value of the elements in the tuple

tuple(seq)

Convert list to tuple

tuple method

method

describe

tuple.count(value)

Count the number of element values ​​in a tuple

tuple.index(value, [start, [stop]])

Returns the index position of the specified element in the column tuple. You can set the search range through the start and stop parameters. If the element does not exist, an exception will be reported

5. Conversion between tuples and lists 

Tuples and lists can be converted to each other

list1 =[1,2,3,45]
tuple1 = (91,2,3,4)
list2 = list(tuple1)
tuple2 = tuple(list1)
print(list2)     #[91, 2, 3, 4]
print(tuple2)     #(1, 2, 3, 45)

6. Advantages of tuples

 You can make a function return multiple values

 Can improve program running performance

Generally speaking, creating variables of tuple type is faster than list type and takes up less storage space.  

Using tuples is thread-safe

The elements of tuple type variables cannot be changed, which can ensure the security issues during multi-threaded reading and writing.

6. Dictionary

1. Creation of dictionary    

  •    Variable name={key1:value1, key2:value2,…, keyn:valuen}
  • The elements (values) of the dictionary are mutable and can be of any data type, but the key (key) value must be an immutable type.  In the same dictionary variable, the key (key) value must be unique .
stu = {"name":"zhangsan","age":21,"sex":"F"}
print(stu)

输出如下:
{'name': 'zhangsan', 'age': 21, 'sex': 'F'}

2. Dictionary access

  • The dictionary is unordered and has no index. Elements can only be obtained by key.
  • You can pass the dictionary name [key] , or you can pass the dictionary name.get("age")
stu = {"name":"zhangsan","age":21,"sex":"F"}
print(stu)print(stu["name"],stu["age"])         #输出为:zhangsan 21
print(stu.get("name"),stu.get("age"))           #输出为:zhangsan 21

3. Modification of dictionary

The code modifies the value value through a reference to the key value.

stu = {"name":"zhangsan","age":21,"sex":"F"}
stu["sex"] ="M"
print(stu)

输出结果如下:
{'name': 'zhangsan', 'age': 21, 'sex': 'M'}

4. Delete dictionary

Delete via del keyword

stu = {"name":"zhangsan","age":21,"sex":"F"}
del stu["age"]
print(stu)

输出如下:
{'name': 'zhangsan', 'sex': 'F'}

5. Addition of dictionary

Format: dictionary name [key] = value

stu = {"name":"zhangsan","age":21,"sex":"F"}
stu["county"] = "China"
print(stu)
输出结果如下:
{'name': 'zhangsan', 'age': 21, 'sex': 'F', 'county': 'China'}

6. Built-in functions related to dictionaries

dictionary function

function

meaning

cmp(dict1, dict2)

Comparing two dictionary elements is no longer available in Python 3

len(dict)

Count the number of dictionary elements

str(dict)

Outputs the printable string representation of the dictionary

dictionary method

method

meaning

radiansdict.clear()

Delete all elements in the dictionary

radiansdict.copy()

Returns a shallow copy of the dictionary

radiansdict.fromkeys()

Create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and val is the initial value corresponding to all keys in the dictionary.

radiansdict.get(key,default=None)

Returns the value of the specified key, or returns the default value if the value is not in the dictionary

radiansdict.has_key(key)

Returns true if the key is in the dictionary dict, false otherwise

radiansdict.items

Returns an iterable array of (key, value) tuples as a list

radiansdict.keys()

Returns all keys of a dictionary as a list

radiansdict.setdefault(key,default=None)

Similar to get(), but if the key does not already exist in the dictionary, the key will be added and the value will be set to default

radiansdict.update(dict2)

Update the dictionary dict2 key/value pairs into the object radiansdict

radiansdict.values()

Returns all values ​​in the dictionary as a list

 7. Collection

1. Creation of collections

  • Format: variable name = {element 1, element 2,…, element n}
  • Sets are very similar to lists, except that lists use [], while sets use {}. They can both be modified, and there are no restrictions on the type of elements.
set1 ={1,2,3,'qwd'}
print(set1)
输出如下:
{'qwd', 1, 2, 3}

2. Characteristics of collections

  • Disorder: There is no definite order among elements.
  • Mutuality: There will be no duplicate elements.
set1 = {1,2,3,5,"123",1,2,3}
print(set1)
输出为:
{1, 2, 3, 5, '123'}

# 输出的顺序不一定按照集合内的元素顺序输出,体现了集合的无序性
# 输出的元素没有重复的,体现了集合的互异性
  • Deterministic: Elements and sets only have a relationship of belonging or not belonging.
set1 = {1,2,3,5,"123",1,2,3}
print(set1)
print(1 in set1)  #True
print( 1 not in set1)  #False

3. Add elements to the collection

  • add(): add an element
  • update(): Add multiple elements at the same time
set1 = {1,2,3,5,"123",1,2,3}
set1.add(23)
print("ste1=",set1)
set2 = {1,2,3,4}
set2.update({5,6,7,8})
print("ste2=",set2)
输出结果如下:
ste1= {1, 2, 3, 5, '123', 23}
ste2= {1, 2, 3, 4, 5, 6, 7, 8}

4. Delete elements from a collection

  • The discard() and remove() methods remove specific elements from a collection
  • If the deleted object does not exist, the remove() method will cause an error, but the discard() method will not

5. Numerical operations on sets

Take set1 = {1,2,3} set2 = {3,4,5}

Arithmetic operations

operator

meaning

example

intersection

&

Get common elements between two sets

 set1 & set2 》{3}

union

|

Get all elements of two sets

 set1 | set2 》{1,2,3,4,5}

difference set

-

Get elements from one set that are not found in another set

 set1 - set2 》{1,2}

 set2 - set1 》{4,5}

Symmetric difference set

^

取集合 A 和 B 中不属于 A&B 的元素

set1 ^ set2  》{1,2,4,5}

6. 集合中的frozenset

  • set 集合是可变序列,程序可以改变序列中的元素
  • frozenset 集合是不可变序列,程序不能改变序列中的元素
set1 ={1,2,3,4}
set2 = frozenset(set1)
# 现在集合set2是一个不可变集合,若对其进行修改,添加,则会报错

到这里python的七大数据类型就介绍完了,如果有什么表述不清楚,或者有错的地方请指正

Guess you like

Origin blog.csdn.net/m0_61232019/article/details/129798969