Python—Chapter 2 Data Types, Operators, and Built-in Functions

Table of contents

1 assignment statement

2 data types

2.1 Common built-in data types

2.1.1 Integers, real numbers, complex numbers

2.1.2 Lists, tuples, dictionaries, sets

 2.1.3 Strings

2.2 Operators and expressions

2.2.1 Arithmetic operators 

2.2.2 Relational operators

2.2.3 Membership test operator

2.2.4 Set operators

2.2.5 Logical operators

2.3 Common built-in functions

2.3.1 Type Conversion

2.3.2 Maximum value, minimum value

2.3.3 Number of elements, summation

2.3.4 Sorting, reverse order 

2.3.5 Basic input and output

2.3.6  range()

2.3.7  zip() 

2.3.8  map()、reduce()、filter()


1 assignment statement

Format: variable name = data

x=2 
x=y=2   #多个变量同时具有相同的值,id(x)查看变量的内存地址 
x,y=1,2  #多个变量同时具有不相同的值 x,y=y,x  #变量交换

2 data types

integer type, string type, list type

2.1 Common built-in data types

2.1.1 Integers, real numbers, complex numbers

import math
print(math.factorial(32))               # 计算32的阶乘
print(0.4-0.3 == 0.1)                   # 实数之间尽量避免直接比较大小
print(math.isclose(0.4-0.3, 0.1))       # 测试两个实数是否足够接近
num = 7
squreRoot = num ** 0.5                  # 计算平方根
print(squreRoot**2 == num)
print(math.isclose(squreRoot**2, num))
---------------------------------------
263130836933693530167218012160000000
False
True
False
True
c = 3+4j                                # Python内置支持复数及其运算
print(c+c)                              # 复数相加
print(c**2)                             # 幂运算
print(c.real)                           # 查看复数的实部
print(c.imag)                           # 查看复数的虚部
print(3+4j.imag)                        # 相当于3+(4j).imag
print(c.conjugate())                    # 查看共轭复数
print(abs(c))                           # 计算复数的模
------------------------------------
(6+8j)
(-7+24j)
3.0
4.0
7.0
(3-4j)
5.0

2.1.2 Lists, tuples, dictionaries, sets

Lists, tuples, dictionaries, and sets are Python's built-in container objects. 

# 创建列表对象
x_list = [1, 2, 3]
# 创建元组对象
x_tuple = (1, 2, 3)
# 创建字典对象,元素形式为“键:值”
x_dict = {'a':97, 'b':98, 'c':99}
# 创建集合对象
x_set = {1, 2, 3}

# 使用下标访问列表中指定位置的元素,元素下标从0开始
print(x_list[1])
# 元组也支持使用序号作为下标,1表示第二个元素的下标
print(x_tuple[1])
# 访问字典中特定“键”对应的“值”,字典对象的下标是“键”
print(x_dict['a'])
# 查看列表长度,也就是其中元素的个数
print(len(x_list))
# 查看元素2在元组中首次出现的位置
print(x_tuple.index(2))
# 查看字典中哪些“键”对应的“值”为98
for key, value in x_dict.items():
    if value == 98:
        print(key)
# 查看集合中元素的最大值
print(max(x_set))
----------------------------------
2
2
97
3
1
b
3

 2.1.3 Strings

Add the English letter r or R in front of the string to indicate the original string, in which each character represents the meaning of the letter, no longer escaped. If the string contains a backslash "\", it is recommended to add the letter r directly in front of the string to use the original string.

text = '''Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.'''

print(len(text))                 # 字符串长度,即所有字符的数量
print(text.count('is'))          # 字符串中单词is出现的次数
print('beautiful' in text)       # 测试字符串中是否包含单词beautiful
print('='*20)                    # 字符串重复
print('Good '+'Morning')         # 字符串连接
---------------------------------------
208
6
False
====================
Good Morning

2.2 Operators and expressions

2.2.1 Arithmetic operators 

(1) + operator

In addition to being used for arithmetic addition, the + operator can also be used for concatenation of lists, tuples, and strings.

print(3 + 5)
print(3.4 + 4.5)
print((3+4j) + (5+6j))
print('abc' + 'def')
print([1,2] + [3,4])
print((1,2) + (3,))
------------------------------
8
7.9
(8+10j)
abcdef
[1, 2, 3, 4]
(1, 2, 3)

(2) - operator

In addition to arithmetic subtraction and inverse numbers between integers, real numbers, and complex numbers, operators can also calculate the difference of sets. It should be noted that errors may occur when performing operations between real numbers. 

print(7.9 - 4.5)                    # 注意,结果有误差
print(5 - 3)
num = 3
print(-num)
print(--num)                        # 注意,这里的--是两个负号,负负得正
print(-(-num))                      # 与上一行代码含义相同
print({1,2,3} - {3,4,5})            # 计算差集
print({3,4,5} - {1,2,3})
--------------------------------------
3.4000000000000004
2
-3
3
3
{1, 2}
{4, 5}

 (3) * operator

In addition to expressing the arithmetic multiplication between integers, real numbers, and complex numbers, the * operator can also be used to multiply objects of types such as lists, tuples, and strings with integers, to represent the repetition of sequence elements, and to generate new lists and tuples or a string. 

print(33333 * 55555)
print((3+4j) * (5+6j))
print('重要的事情说三遍!' * 3)
print([0] * 5)
print((0,) * 3)
--------------------------------------
1851814815
(-9+38j)
重要的事情说三遍!重要的事情说三遍!重要的事情说三遍!
[0, 0, 0, 0, 0]
(0, 0, 0)

(4) Operators / and //

Represents true division and integer quotient respectively in Python. When using it, pay special attention to the feature of the integer division operator //"round down". For example, the result of -17/4 is -4.25, and the largest integer less than -4.25 on the number line is -5, so the result of -17//4 is -5.

print(17 / 4)
print(17 // 4)
print((-17) / 4)
print((-17) // 4)
--------------------------
4.25
4
-4.25
-5

(5) % operator

The % operator can be used for remainder operations and for string formatting. When calculating the remainder, the result matches the sign of the operand to the right of %.

print(365 % 7)
print(365 % 2)
print('%c,%c, %c' % (65, 97, 48))   # 把65、97、48格式化为字符
---------------------------------------
1
1
A,a, 0

(6) ** operator

The ** operator represents exponentiation. When using it, it should be noted that this operator has right associativity, that is, if there are two consecutive ** operators, the right one is calculated first and then the left one, unless parentheses are used to explicitly modify the calculation order of expressions.

print(2 ** 4)
print(3 ** 3 ** 3)
print(3 ** (3**3))           # 与上一行代码含义相同
print((3**3) ** 3)           # 使用圆括号修改计算顺序
print(9 ** 0.5)              # 计算9的平方根
print((-1) ** 0.5)           # 对复数计算平方根得到复数
--------------------------------------
16
7625597484987
7625597484987
19683
3.0
(6.123233995736766e-17+1j)

2.2.2 Relational operators

print(3+2 < 7+8)                          # 关系运算符优先级低于算术运算符
print(3 < 5 > 2)                          # 等价于3<5 and 5>2
print(3 == 3 < 5)                         # 等价于3==3 and 3<5
print('12345' > '23456')                  # 第一个字符'1'<'2',直接得出结论
print('abcd' > 'Abcd')                    # 第一个字符'a'>'A',直接得出结论
print([85, 92, 73, 84] < [91, 82, 73])    # 第一个数字85<91,直接得出结论
print([180, 90, 101] > [180, 90, 99])     # 前两个数字相等,第三个数字101>99
print({1, 2, 3, 4} > {3, 4, 5})           # 第一个集合不是第二个集合的超集
print({1, 2, 3, 4} <= {3, 4, 5})          # 第一个集合不是第二个集合的子集
print([1, 2, 3, 4] > [1, 2, 3])           # 前三个元素相等
                                          # 并且第一个列表有多余的元素
----------------------------------
True
True
True
False
True
True
True
False
False
True

2.2.3 Membership test operator

print(60 in [70, 60, 50, 80])
print('abc' in 'a1b2c3dfg')
print([3] in [[3], [4], [5]])
print('3' in map(str, range(5)))
print(5 in range(5))
-----------------------------------
True
False
True
True
False

2.2.4 Set operators

A = {35, 45, 55, 65, 75}
B = {65, 75, 85, 95}
print(A | B)
print(A & B)
print(A - B)
print(B - A)
print(A ^ B)
------------------------------
{65, 35, 75, 45, 85, 55, 95}
{65, 75}
{35, 45, 55}
{85, 95}
{35, 45, 85, 55, 95}

2.2.5 Logical operators

Computation results that are not 0, 0.0, 0j, None, False, empty list, empty tuple, empty string, empty dictionary, empty collection, empty range object, or other empty container object are considered equivalent to True.

print(3 in range(5) and 'abc' in 'abcdefg')
print(3-3 or 5-2)
print(not 5)
print(not [])
-------------------------------------------
True
3
False
True

2.3 Common built-in functions

In Python programs, built-in functions can be used directly without importing any modules.

Use the statement print(dir(__builtins__)) to view all built-in functions and built-in objects. Note that there are two underscores on both sides of builtins, a total of 4.

2.3.1 Type Conversion

(1)int()、float()、complex()

print(int(3.5))                 # 获取实数的整数部分
print(int('119'))               # 把整数字符串转换为整数
print(int('1111', 2))           # 把1111看作二进制数,转换为十进制数
print(int('1111', 8))           # 把1111看作八进制数,转换为十进制数
print(int('1111', 16))          # 把1111看作十六进制数,转换为十进制数
print(int('  9\n'))             # 自动忽略字符串两个的空白字符
print(float('3.1415926'))       # 把字符串转换为实数
print(float('-inf'))            # 负无穷大
print(complex(3, 4))            # 复数
print(complex(6j))
print(complex('3'))
----------------------------------------------
3
119
15
585
4369
9
3.1415926
-inf
(3+4j)
6j
(3+0j)

(2)bin()、oct()、hex()

print(bin(8888))              # 把整数转换为二进制
print(oct(8888))              # 把整数转换为八进制
print(hex(8888))              # 把整数转换为十六进制
-------------------------------------------
0b10001010111000
0o21270
0x22b8
1

(3)ord()、chr()、str() 

print(ord('a'))               # 返回字符的ASCII码
print(ord('董'))              # 返回汉字字符的Unicode编码
print(chr(65))                # 返回指定ASCII码对应的字符
print(chr(33891))             # 返回指定Unicode编码对应的汉字
print(str([1, 2, 3, 4]))      # 把列表转换为字符串
print(str({1, 2, 3, 4}))      # 把集合转换为字符串
----------------------------------------------------
97
33891
A
董
[1, 2, 3, 4]
{1, 2, 3, 4}

(4)list()、tuple()、dict()、set()

print(list(), tuple(), dict(), set())  
s = {3, 2, 1, 4}
print(list(s), tuple(s))
lst = [1, 1, 2, 2, 3, 4]
# 在转换为集合时会自动去除重复的元素
print(tuple(lst), set(lst))
# list()会把字符串中每个字符都转换为列表中的元素
# tuple()、set()函数也具有类似的特点
print(list(str(lst)))
print(dict(name='Dong', sex='Male', age=41))
---------------------------------------------
[] () {} set()
[1, 2, 3, 4] (1, 2, 3, 4)
(1, 1, 2, 2, 3, 4) {1, 2, 3, 4}
['[', '1', ',', ' ', '1', ',', ' ', '2', ',', ' ', '2', ',', ' ', '3', ',', ' ', '4', ']']
{'name': 'Dong', 'sex': 'Male', 'age': 41}

(5)eval()

  • Computes the value of a string or byte string
  • Implement the function of type conversion
  • Restore the actual type of the data in the string
print(eval('3+4j'))              # 对字符串求值得到复数
print(eval('8**2'))              # 计算表达式8**2的值
print(eval('[1, 2, 3, 4, 5]'))   # 对字符串形式求值得到列表
print(eval('{1, 2, 3, 4}'))      # 对字符串求值得到集合
---------------------------------------------------
(3+4j)
64
[1, 2, 3, 4, 5]
{1, 2, 3, 4}

2.3.2 Maximum value, minimum value

data = [3, 22, 111]
print(data)
# 对列表中的元素直接比较大小,输出最大元素
print(max(data))
print(min(data))
# 返回转换成字符串之后最大的元素
print(max(data, key=str))
data = ['3', '22', '111']
print(max(data))
-------------------------------------------
[3, 22, 111]
111
3
3
3
# 返回长度最大的字符串
print(max(data, key=len))
data = ['abc', 'Abcd', 'ab']
# 最大的字符串
print(max(data))
# 长度最大的字符串
print(max(data, key=len))
# 全部转换为小写之后最大的字符串
print(max(data, key=str.lower))
data = [1, 1, 1, 2, 2, 1, 3, 1]
------------------------------------
111
abc
Abcd
Abcd
# 出现次数最多的元素
# 也可以查阅资料使用标准库collections中的Counter类实现
print(max(set(data), key=data.count))
# 最大元素的位置,列表方法__getitem__()用于获取指定位置的值
print(max(range(len(data)), key=data.__getitem__))
----------------------------------------------------------
1
6

2.3.3 Number of elements, summation

data = [1, 2, 3, 4]
# 列表中元素的个数
print(len(data))
# 所有元素之和
print(sum(data))
data = (1, 2, 3)
print(len(data))
print(sum(data))
---------------------
4
10
3
6
data = {1, 2, 3}
print(len(data))
print(sum(data))
data = 'Readability counts.'
print(len(data))
data = {97: 'a', 65: 'A', 48: '0'}
print(len(data))
print(sum(data))
------------------------------------
3
6
19
3
210

2.3.4 Sorting, reverse order 

(1)sorted

sorted() can sort lists, tuples, dictionaries, collections or other iterable objects and return a new list. It supports using the key parameter to specify the sorting rules. The value of the key parameter can be a function, class, lambda expression, method, etc. call object.

In addition, you can also use the reverse parameter to specify whether to sort in ascending order (reverse=False) or descending order (reverse=True). If not specified, the default is ascending order.

from random import shuffle

data = list(range(20))
shuffle(data)                  # 随机打乱顺序
print(data)
print(sorted(data))            # 升序排序
print(sorted(data, key=str))   # 按转换成字符串后的大小升序排序
print(sorted(data, key=str,    # 按转换成字符串后的大小
             reverse=True))    # 降序排序
----------------------------------------------------------------------
[5, 3, 0, 10, 1, 11, 8, 2, 9, 13, 16, 6, 17, 19, 15, 7, 12, 4, 14, 18]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 1, 0]

(2)reversed

reversed() can reverse iterable objects (except generator objects and zip, map, filter, enumerate, reversed and other similar objects with lazy evaluation characteristics) and return iterable reversed objects.

When using it, it should be noted that the reversed object has the characteristics of lazy evaluation, and the elements in it can only be used once, and it does not support using the built-in function len() to calculate the number of elements, nor does it support using the built-in function reversed() to flip again.

from random import shuffle

data = list(range(20))        # 创建列表
shuffle(data)                 # 随机打乱顺序
print(data)
reversedData = reversed(data) # 生成reversed对象
print(reversedData)
print(list(reversedData))     # 根据reversed对象得到列表
print(tuple(reversedData))    # 空元组,reversed对象中元素只能使用一次
--------------------------------------------------------------------------
[3, 19, 6, 17, 11, 5, 18, 15, 8, 1, 12, 7, 16, 4, 14, 10, 0, 9, 13, 2]
<list_reverseiterator object at 0x000001B79034F700>
[2, 13, 9, 0, 10, 14, 4, 16, 7, 12, 1, 8, 15, 18, 5, 11, 17, 6, 19, 3]
()

2.3.5 Basic input and output

(1) Built-in function input

The built-in function input() is used to receive the user's keyboard input. No matter what the user enters, input() will be treated as a string. When necessary, the built-in function int(), float() or eval() can be used to process the user's input. The content is typecast.

num = int(input('请输入一个大于2的自然数:'))
# 对2的余数为1的整数为奇数,能被2整除的整数为偶数
if num%2 ==1:
    print('这是个奇数。')
else:
    print('这是个偶数。')

lst = eval(input('请输入一个包含包含若干大于2的自然数的列表:'))
print('列表中所有元素之和为:', sum(lst))
-----------------------------------------------------------------
请输入一个大于2的自然数:6
这是个偶数。
请输入一个包含包含若干大于2的自然数的列表:[4,7,8,9]
列表中所有元素之和为: 28

(2) Built-in function print

The built-in function print() is used to output information in a specified format, and the syntax format is:

print(value1, value2, ..., sep=' ', end='\n')

Among them, before the sep parameter is the content to be output (there can be more than one); the sep parameter is used to specify the separator between the data, if not specified, it will be a space by default; the end parameter indicates the end character after all the data is output, if If not specified, it defaults to a newline.

print(1, 2, 3, 4, 5)            # 默认情况,使用空格作为分隔符
print(1, 2, 3, 4, 5, sep=',')   # 指定使用逗号作为分隔符
print(3, 5, 7, end=' ')         # 输出完所有数据之后,以空格结束,不换行
print(9, 11, 13)
--------------------------------------------------
1 2 3 4 5
1,2,3,4,5
3 5 7 9 11 13

2.3.6  range()

range([start,] stop [,step])

Among them, the parameter start defaults to 0, step defaults to 1, and the left open and right close interval [start, stop)

  • range(stop)
  • range(start,stop)
  • range(start,stop,step)
range1 = range(4)           # 只指定stop为4,start默认为0,step默认为1
range2 = range(5, 8)        # 指定start=5和stop=8,step默认为1
range3 = range(3, 20, 4)    # 指定start=3、stop=20和step=4
range4 = range(20, 0, -3)   # step也可以是负数
print(range1, range2, range3, range4)
print(range4[2])
print(list(range1), list(range2), list(range3), list(range4))
for i in range(10):
    print(i, end=' ')
------------------------------------------------------------------
range(0, 4) range(5, 8) range(3, 20, 4) range(20, 0, -3)
14
[0, 1, 2, 3] [5, 6, 7] [3, 7, 11, 15, 19] [20, 17, 14, 11, 8, 5, 2]
0 1 2 3 4 5 6 7 8 9 

2.3.7  zip() 

zip() is used to combine the elements at the corresponding positions in multiple iterable objects together, and return an iterable zip object, in which each element is the element containing the elements at the corresponding positions of the original multiple iterable objects Group, the number of elements contained in the final result is determined by the shortest of all argument sequences or iterable objects.

Each element in the zip object can only be used once, and the elements that have been visited cannot be accessed again, and the elements in the zip object can only be accessed one by one from front to back, and the elements at the specified position cannot be directly accessed using subscripts.

data = zip('1234', [1, 2, 3, 4, 5, 6])
print(data)
# 在转换为列表时,使用了zip对象中的全部元素,zip对象中不再包含任何内容
print(list(data))
# 如果需要再次访问其中的元素,必须重新创建zip对象
data = zip('1234', [1, 2, 3, 4, 5, 6])
print(tuple(data))
data = zip('1234', [1, 2, 3, 4, 5, 6])
# zip对象是可迭代的,可以使用for循环逐个遍历和访问其中的元素
for item in data:
    print(item)
---------------------------------------------------------
<zip object at 0x000001B790734940>
[('1', 1), ('2', 2), ('3', 3), ('4', 4)]
(('1', 1), ('2', 2), ('3', 3), ('4', 4))
('1', 1)
('2', 2)
('3', 3)
('4', 4)

2.3.8  map()、reduce()、filter()

(1)map()

map(func,*iterables)

The map() function maps a callable object func to each element of the sequence in turn, and returns an optional generation map object, where each element is the result of processing the elements in the original sequence through the callable object func. The function does not make any modification to the original sequence. The map object returned by this function can be converted into a list, tuple or set, or directly use the for loop to traverse the elements in it, but each element in the map object can only be used once.

from operator import add

print(map(str, range(5)))
print(list(map(str, range(5))))
print(list(map(len, ['abc', '1234', 'test'])))
# 使用operator标准库中的add运算add运算相当于运算符+
# 如果map()函数的第一个参数func能够接收两个参数,则可以映射到两个序列上
for num in map(add, range(5), range(5,10)):
    print(num)
--------------------------------------------------
<map object at 0x000001B79034F400>
['0', '1', '2', '3', '4']
[3, 4, 4]
5
7
9
11
13

(2)reduce()

reduce(func,seq[,initial])

reduce() can apply a function that receives two parameters to all elements of a sequence or iterable object in an iterative manner from left to right, and the intermediate results of each calculation directly participate in the next calculation, and finally get a value.

from functools import reduce
from operator import add, mul, or_

seq = range(1, 10)
print(reduce(add, seq))       # 累加seq中的数字
print(reduce(mul, seq))       # 累乘seq中的数字
seq = [{1}, {2}, {3}, {4}]
print(reduce(or_, seq))       # 对seq中的集合连续进行并集运算
-------------------------------------------------------
45
362880
{1, 2, 3, 4}

(3)filter()

filter(func or None, iterable)

filter. Apply a function func to a sequence, and return a filter object containing elements in the original sequence that make the return value of function func equal to True. Each element can only be used once.

seq = ['abcd', '1234', '.,?!', '']
print(list(filter(str.isdigit, seq)))   # 只保留数字字符串
print(list(filter(str.isalpha, seq)))   # 只保留英文字母字符串
print(list(filter(str.isalnum, seq)))   # 只保留数字字符串和英文字符串
print(list(filter(None, seq)))          # 只保留等价于True的元素
------------------------------------------------------
['1234']
['abcd']
['abcd', '1234']
['abcd', '1234', '.,?!']

 From the book: "Python Data Analysis, Mining and Visualization"

Guess you like

Origin blog.csdn.net/J__aries/article/details/130233383