[Python] Python Series Tutorials--Python3 Basic Data Types (5)

foreword

Past review:

Variables in Python do not need to be declared. Each variable must be assigned a value before use, and the variable will not be created until the variable is assigned.

In Python, a variable is a variable, it doesn't have a type, what we mean by "type" is the type of object in memory that the variable refers to.

The equal sign (=) is used to assign values ​​to variables.

The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable. For example:

Example (Python 3.0+)

#!/usr/bin/python3

counter = 100          # 整型变量
miles   = 1000.0       # 浮点型变量
name    = "runoob"     # 字符串

print (counter)
print (miles)
print (name)

Run the example»
Execute the above program and the following results will be output:

100
1000.0
runoob

multiple variable assignment

Python allows you to assign values ​​to multiple variables at the same time. For example:

a = b = c = 1

In the above example, create an integer object with a value of 1, and assign values ​​from the back to the front, and the three variables are assigned the same value.

You can also specify multiple variables for multiple objects. For example:

a, b, c = 1, 2, “runoob”

In the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "runoob" is assigned to variable c.

standard data type

There are six standard data types in Python3:

  • Number
  • String (string)
  • List (list)
  • Tuple
  • Set (collection)
  • Dictionary

Among the six standard data types of Python3:

  • Immutable data (3): Number (number), String (string), Tuple (tuple);
  • Variable data (3): List (list), Dictionary (dictionary), Set (collection).

Number

Python3 supports int, float, bool, complex (complex numbers).

In Python 3, there is only one integer type int, which is represented as a long integer, and there is no Long in python2.

Like most languages, assignment and evaluation of numeric types is straightforward.

The built-in type() function can be used to query the type of object a variable refers to.

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

In addition, isinstance can also be used to judge:

example

>>> a = 111
>>> isinstance(a, int)
True
>>>

The difference between isinstance and type is:

  • type() will not consider the subclass to be a superclass type.
  • isinstance() will consider the child class to be a parent class type.
>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> isinstance(A(), A)
True
>>> type(A()) == A 
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False

Note: In Python3, bool is a subclass of int, True and False can be added to numbers, True1、False0 will return True, but the type can be judged by is.

>>> issubclass(bool, int) 
True
>>> True==1
True
>>> False==0
True
>>> True+1
2
>>> False+1
1
>>> 1 is True
False
>>> 0 is False
False

There is no Boolean type in Python2, it uses the number 0 to represent False and 1 to represent True.

Number objects are created when you specify a value:

var1 = 1
var2 = 10

You can also delete some object references using the del statement.

The syntax of the del statement is:

del var1[,var2[,var3[…,varN]]]

You can delete single or multiple objects by using the del statement. For example:

part var part var_a, var_b

Numerical operations

example

>>> 5 + 4  # 加法
9
>>> 4.3 - 2 # 减法
2.3
>>> 3 * 7  # 乘法
21
>>> 2 / 4  # 除法,得到一个浮点数
0.5
>>> 2 // 4 # 除法,得到一个整数
0
>>> 17 % 3 # 取余
2
>>> 2 ** 5 # 乘方
32

Notice:

1. Python can assign values ​​to multiple variables at the same time, such as a, b = 1, 2.
2. A variable can point to different types of objects through assignment.
3. Numerical division contains two operators: / returns a floating point number, // returns an integer.
4. During mixed calculations, Python will convert integers to floating-point numbers.

Numeric type instance

int float complex
10 0.0 3.14y
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3e+18. 876j
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2E-12 4.53e-7j

Python also supports complex numbers. A complex number consists of a real part and an imaginary part. It can be represented by a + bj, or complex(a,b). The real part a and the imaginary part b of a complex number are both floating-point types.

String (string)

Strings in Python are enclosed in single quotes ' or double quotes ", and special characters are escaped with a backslash \.

The grammatical format of string interception is as follows:

variable [head subscript: tail subscript]

Index values ​​start at 0 and start at -1 from the end.

insert image description here

The plus sign + is the connector of the string, the asterisk * means to copy the current string, and the number combined with it is the number of times of copying. Examples are as follows:

example

#!/usr/bin/python3

str = 'Runoob'

print (str)          # 输出字符串
print (str[0:-1])    # 输出第一个到倒数第二个的所有字符
print (str[0])       # 输出字符串第一个字符
print (str[2:5])     # 输出从第三个开始到第五个的字符
print (str[2:])      # 输出从第三个开始的后的所有字符
print (str * 2)      # 输出字符串两次,也可以写成 print (2 * str)
print (str + "TEST") # 连接字符串

Executing the above program will output the following results:

Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTEST

Python uses the backslash \ to escape special characters. If you don’t want the backslash to be escaped, you can add an r in front of the string to represent the original string:

example

>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob
>>>

In addition, the backslash () can be used as a continuation character, indicating that the next line is a continuation of the previous line. You can also use """…""" or '''…''' to span multiple lines.

Note that Python does not have a separate character type, a character is a string of length 1.

example

>>> word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n P

Unlike C strings, Python strings cannot be changed. Assigning a value to an index position, such as word[0] = 'm' will cause an error.

Notice:

1. Backslashes can be used for escaping, and r can be used to prevent backslashes from escaping.
2. Strings can be concatenated with the + operator and repeated with the * operator.
3. Strings in Python have two indexing methods, starting with 0 from left to right, and starting with -1 from right to left.
4. Strings in Python cannot be changed.

List (list)

List (list) is the most frequently used data type in Python.

Lists can complete the data structure implementation of most collection classes. The types of elements in the list can be different, it supports numbers, strings can even contain lists (so-called nesting).

A list is a comma-separated list of elements written between square brackets [].

Like strings, lists can also be indexed and truncated. After the list is truncated, a new list containing the required elements is returned.

The syntax format of list interception is as follows:

variable [head subscript: tail subscript]

Index values ​​start at 0 and start at -1 from the end.

insert image description here

The plus sign + is the list concatenation operator and the asterisk * is the repetition operation. Examples are as follows:

example

#!/usr/bin/python3

list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ]
tinylist = [123, 'runoob']

print (list)            # 输出完整列表
print (list[0])         # 输出列表第一个元素
print (list[1:3])       # 从第二个开始输出到第三个元素
print (list[2:])        # 输出从第三个元素开始的所有元素
print (tinylist * 2)    # 输出两次列表
print (list + tinylist) # 连接列表

The output of the above example:

['abcd', 786, 2.23, 'runoob', 70.2]
abcd
[786, 2.23]
[2.23, 'runoob', 70.2]
[123, 'runoob', 123, 'runoob']
['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']

Unlike Python strings, elements in lists can be changed:

example

>>> a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = []   # 将对应的元素值设置为 []
>>> a
[9, 2, 6]

List has many built-in methods, such as append(), pop(), etc., which will be mentioned later.

Notice:

1. List is written between square brackets, and elements are separated by commas.
2. Like strings, lists can be indexed and sliced.
3. List can be spliced ​​using + operator.
4. The elements in the List can be changed.
Python list interception can receive the third parameter, which is the step size of the interception. The following example is at the index 1 to index 4 and set the step size to 2 (one position apart) to intercept the string:

insert image description here

If the third parameter is negative, it means reverse reading, the following example is used to reverse the string:

example

def reverseWords(input):
     
    # 通过空格将字符串分隔符,把各个单词分隔为列表
    inputWords = input.split(" ")
 
    # 翻转字符串
    # 假设列表 list = [1,2,3,4],  
    # list[0]=1, list[1]=2 ,而 -1 表示最后一个元素 list[-1]=4 ( 与 list[3]=4 一样)
    # inputWords[-1::-1] 有三个参数
    # 第一个参数 -1 表示最后一个元素
    # 第二个参数为空,表示移动到列表末尾
    # 第三个参数为步长,-1 表示逆向
    inputWords=inputWords[-1::-1]
 
    # 重新组合字符串
    output = ' '.join(inputWords)
     
    return output
 
if __name__ == "__main__":
    input = 'I like runoob'
    rw = reverseWords(input)
    print(rw)

The output is:

runoob like I

Tuple

A tuple is similar to a list, except that the elements of a tuple cannot be modified. Tuples are written in parentheses (), and elements are separated by commas.

The element types in the tuple can also be different:

example

#!/usr/bin/python3

tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2  )
tinytuple = (123, 'runoob')

print (tuple)             # 输出完整元组
print (tuple[0])          # 输出元组的第一个元素
print (tuple[1:3])        # 输出从第二个元素开始到第三个元素
print (tuple[2:])         # 输出从第三个元素开始的所有元素
print (tinytuple * 2)     # 输出两次元组
print (tuple + tinytuple) # 连接元组

The output of the above example:

('abcd', 786, 2.23, 'runoob', 70.2)
abcd
(786, 2.23)
(2.23, 'runoob', 70.2)
(123, 'runoob', 123, 'runoob')
('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')

Similar to strings, tuples can be indexed and the subscript index starts from 0, and -1 is the position from the end. Interception can also be performed (see above, no more details here).

In fact, strings can be thought of as a special kind of tuple.

example

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11  # 修改元组元素的操作是非法的
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>

Although the elements of a tuple are immutable, it can contain mutable objects, such as lists.

Constructing tuples with 0 or 1 elements is special, so there are some additional syntax rules:

tup1 = ()    # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

string, list and tuple all belong to sequence (sequence).

Notice:

1. Like strings, elements of tuples cannot be modified.
2. Tuples can also be indexed and sliced ​​in the same way.
3. Pay attention to the special syntax rules for constructing tuples containing 0 or 1 elements.
4. Tuples can also be concatenated using the + operator.

Set (collection)

A set is composed of one or several wholes of various shapes and sizes, and the things or objects that constitute a set are called elements or members.

The basic functionality is to perform membership tests and remove duplicate elements.

You can use braces { } or the set() function to create a collection. Note: To create an empty collection, you must use set() instead of { }, because { } is used to create an empty dictionary.

Create format:

parame = {
    
    value01,value02,...}
或者
set(value)

example

#!/usr/bin/python3

sites = {
    
    'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}

print(sites)   # 输出集合,重复的元素被自动去掉

# 成员测试
if 'Runoob' in sites :
    print('Runoob 在集合中')
else :
    print('Runoob 不在集合中')


# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')

print(a)

print(a - b)     # a 和 b 的差集

print(a | b)     # a 和 b 的并集

print(a & b)     # a 和 b 的交集

print(a ^ b)     # a 和 b 中不同时存在的元素

The output of the above example:

{
    
    'Zhihu', 'Baidu', 'Taobao', 'Runoob', 'Google', 'Facebook'}
Runoob 在集合中
{
    
    'b', 'c', 'a', 'r', 'd'}
{
    
    'r', 'b', 'd'}
{
    
    'b', 'c', 'a', 'z', 'm', 'r', 'l', 'd'}
{
    
    'c', 'a'}
{
    
    'z', 'b', 'm', 'r', 'l', 'd'}

Dictionary

Dictionaries are another very useful built-in data type in Python.

A list is an ordered collection of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by key, not by offset.

A dictionary is a mapping type, and the dictionary is marked with { }, which is an unordered key (key): value (value) collection.

Keys must use immutable types.

Within the same dictionary, keys must be unique.

example

#!/usr/bin/python3

dict = {
    
    }
dict['one'] = "1 - 菜鸟教程"
dict[2]     = "2 - 菜鸟工具"

tinydict = {
    
    'name': 'runoob','code':1, 'site': 'www.runoob.com'}


print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值

The output of the above example:

1 - 菜鸟教程
2 - 菜鸟工具
{
    
    'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['runoob', 1, 'www.runoob.com'])

The constructor dict() can directly construct a dictionary from a sequence of key-value pairs as follows:

example

>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{
    
    'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>> {
    
    x: x**2 for x in (2, 4, 6)}
{
    
    2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{
    
    'Runoob': 1, 'Google': 2, 'Taobao': 3}

{x: x**2 for x in (2, 4, 6)} This code uses dictionary comprehension. For more derivation content, please refer to: Python derivation.

In addition, the dictionary type also has some built-in functions, such as clear(), keys(), values(), etc.

Notice:

1. A dictionary is a mapping type whose elements are key-value pairs.
2. The keywords of the dictionary must be immutable and cannot be repeated.
3. Create an empty dictionary using { }.

Python data type conversion

Sometimes, we need to convert the built-in data type. For data type conversion, you only need to use the data type as the function name. In the next chapter, Python3 data type conversion will be introduced in detail.

The following built-in functions can perform conversions between data types. These functions return a new object representing the converted value.

function describe
int(x [,base]) convert x to an integer
float(x) Convert x to a float
complex(real [,imag]) create a plural
str(x) convert the object x to a string
repr(x) Convert the object x to an expression string
eval(str) Evaluates a valid Python expression in a string and returns an object
tuple(s) convert the sequence s to a tuple
list(s) convert the sequence s to a list
set(s) convert to a mutable collection
dict(d) Create a dictionary. d must be a sequence of (key, value) tuples.
frozenset(s) Convert to immutable collection
chr(x) Convert an integer to a character
ord(x) converts a character to its integer value
hex(x) Convert an integer to a hexadecimal string
oct(x) converts an integer to an octal string

Guess you like

Origin blog.csdn.net/u011397981/article/details/130999519