Python Basics (2) | Basic Data Types of Python

timerring 2022-09-09 03:19:02 阅读数:209

pythonbasicsbasicdatatypes

第二章 基本数据类型

This column aims to correctPythonThe basic syntax is explained in detail,A concise summary of the main points in the grammar,Explain the difficulty in detail,For beginners and beginners,You can master it through the study of the columnpython编程,At the same time for subsequent data analysis,Lay a solid foundation for coding capabilities in machine learning and deep learning.

本文已收录于PythonBasic series column: Python基础系列教程 欢迎订阅,持续更新.

image-20220908151914154

第一部分 数字类型

image-20220908152001501

1.1 Composition of numeric types

1.1.1 整数——不同进制的转换

  • Decimal is entered by default
  • 二进制0b、八进制0o、十六进制0x
16 == 0b10000 == 0o20 == 0x10
True
  • Conversion from decimal to other bases
a = bin(16) # 转二进制
b = oct(16) # 转八进制
c = hex(16) # 转十六进制
print(a, b, c)
0b10000 0o20 0x10

注意:The result of the above conversion is a string type,So if an equality comparison is made,输出的是False结果

a == b == c
False
type(a)
str
  • 其他进制转十进制
d = int(a, 2) # 二进制转十进制
e = int(b, 8) # 八进制转十进制
f = int(c, 16) # 十六进制转十进制
print(d, e, f)
16 16 16

1.1.2 浮点数——不确定性

  • Not sure about decimals
(0.1+0.2) == 0.3
False
0.1+0.2
0.30000000000000004

Computers use binary decimals to represent the fractional part of floating-point numbers

  • 原因:部分小数不能用二进制小数完全表示

    二进制 十进制
    

    0.00011001100110011001 0.09999942779541016
    0.0011001100110011 0.1999969482421875
    0.01001100110011001 0.29999542236328125
    0.01100110011001101 0.40000152587890625
    0.1 === 1 ∗ 2 − 1 1*2^{-1} 121 === 0.5

  • 通常情况下不会影响计算精度

0.1 + 0.7
0.7999999999999999
  • 四舍五入获得精确解
  • It can be solved by rounding:round(parameter, 保留小数位数)
a = 3*0.1
print(a)
0.30000000000000004
b = round(a, 1)
print(b)
b == 0.3
0.3
True

1.1.3 复数——a+bj

  • 大写J或小写j均可
3+4j
2+5J
(2+5j)
  • 虚部系数为1时,需要显式写出
2+1j

1.2 数字运算操作符(a 操作符 b)

  • 加减乘除运算 + - / *
(1+3-4*2)/5
-0.8
  • 取反 -
x = 1
-x
-1
  • 乘方运算 **
2**3
8
  • 整数商// 和 模运算%
13//5 # 整数商 x/y 向下取整数
2
13 % 5 # 模运算 余数 13=2*5+3

几点说明

  • 整数与浮点数运算结果是浮点数
  • 除法运算的结果是浮点数
1+1.5
2.5
2/5
0.4
8/4
2.0

1.3 数字运算操作函数 function(x, …)

  • 求绝对值 abs()
abs(-5)
5
abs(3+4j) # 对复数a+bj 执行的是求模运算(a^2+b^2)^0.5
5.0
  • 幂次方 pow(x,n)
  • Modulo the power pow(x,n,m)
pow(2, 5) # pow(x,n) x的n次方 等价于x**n
32
pow(2, 5, 3) # 2^5 % 3 更快速
2
  • 四舍五入 round(x,n)
a = 1.618
print(round(a)) # The default is rounded to an integer
2
print(round(a, 2)) # 参数2Indicates rounded and retained2位小数
1.62
print(round(a, 5)) # 位数不足,无需补齐
1.618
  • Integer quotient and modulo arithmetic divmod(x,y)

Equivalent to returning a 2-tuple(x//y,x % y)

divmod(13, 5) # 较(x//y,x % y)更快,只执行了一次x/y
(2, 3)
  • 序列最大/最小值 max( ) min( )
max(3, 2, 3, 6, 9, 4, 5)
9
a = [3, 2, 3, 6, 9, 4, 5]
print("max:", max(a))
print("min:", min(a))
max: 9
min: 2
  • 求和sum(x)

注意:sumIt needs to be filled with a sequence data

sum((1, 2, 3, 4, 5))
15
  • 借助科学计算库 math\scipy\numpy
import math # 导入库
print(math.exp(1)) # 指数运算 e^x
print(math.log2(2)) # 对数运算
print(math.sqrt(4)) # 开平方运算 等价于4^0.5
2.718281828459045
1.0
2.0
import numpy as np
a = [1, 2, 3, 4, 5]
print(np.mean(a)) # 求均值
print(np.median(a)) # 求中位数
print(np.std(a)) # 求标准差
3.0
3.0
1.4142135623730951

第二部分 字符串类型

image-20220908152013247

2.1 字符串的表达

  • 用""或’'括起来的任意字符
print("Python")
print('Python')
Python
Python
  • Cases where there are double or single quotes in the string

双中有单

print("I'm 18 years old")
I'm 18 years old

单中有双

print('"Python" is good')
"Python" is good

双中有双,单中有单——转义符 \

# print(""Python" is good")
print("\"Python\" is good") # \ 字符
"Python" is good

Escape characters can be used to continue typing on a new line

s = "py\
thon"
print(s)
python

2.2 字符串的性质

2.2.1 字符串的索引

s = "My name is Peppa Pig"

变量名[位置编号]

  • 正向索引——从零开始递增
  • The position number cannot exceed the length of the string
  • A space is also a position
print(s[0])
print(s[2])
print(s[5])
M
m
s = "My name is Peppa Pig"
  • 反向索引——从-1开始递减
print(s[-1])
print(s[-3])
print(s[-5])
g
P
a

The index can only get one character,How to get multiple characters?

2.2.2 字符串的切片

变量名[开始位置:结束位置:切片间隔]

  • If the slice interval is not set, it defaults to 1,可省略
  • The slice range does not contain an end position(前闭后开)
s = "Python"
print(s[0:3:1])
Pyt
print(s[0:3])
Pyt
print(s[0:3:2])
Pt
  • 起始位置是0 可以省略
  • 结束位置省略,Indicates that the last character can be taken
  • Inverted indexes can be used
s = "Python"
print(s[0:6])
Python
print(s[:6])
Python
print(s[:])
Python
print(s[-6:])
Python

反向切片

  • 起始位置是-1也可以省略
  • 结束位置省略,Indicates that the first character can be taken
  • 关键点在于-1,Represents that the previous position is larger than the next position-1
s = "123456789"
print(s[-1:-10:-1])
987654321
print(s[:-10:-1])
987654321
print(s[::-1])
987654321

2.3 字符串操作符

2.3.1 字符串的拼接

  • 字符串1+字符串2
a = "I love "
b = "my wife "
a+b
'I love my wife '

2.3.2 字符串的成倍复制

  • 字符串 * n n * 字符串
c = a+b
print(c*3)
print(3*c)
I love my wife I love my wife I love my wife
I love my wife I love my wife I love my wife

2.2.3 成员运算

  • 子集in全集 任何一个consecutive slicesBoth are subsets of the original string
folk_singers = "Peter, Paul and Mary"
"Peter" in folk_singers
True
"PPM" in folk_singers
False
  • 遍历字符串字符 for 字符 in 字符串
for s in "Python":
print(s)
P
y
t
h
o
n

2.4 字符串处理函数

2.4.1 字符串的长度

  • The number of characters contained
s = "python"
len(s)
6

2.4.2 字符编码

The Chinese font library,英文字母、数字、Special characters, etc. are converted into binary numbers that can be recognized by the computer

  • Each single character corresponds to a unique non-repeating binary code
  • Python 中使用的是Unicode编码

将字符转化为Unicode码——ord(字符)

print(ord("1"))
print(ord("a"))
print(ord("*"))
print(ord("中"))
print(ord("国"))
49
97
42
20013
22269

将Unicode码转化为字符——chr(Unicode码)

print(chr(1010))
print(chr(10000))
print(chr(12345))
print(chr(23456))
ϲ
*
〹
宠

2.5 字符串的处理方法

2.5.1 字符串的分割——字符串.split(分割字符)

  • 返回一个列表
  • 原字符串不变

The above properties apply to all of the following string processing methods

languages = "Python C C++ Java PHP R"
languages_list = languages.split(" ")#The parameter in parentheses is the token we want to split the target string
print(languages_list)
print(languages)
['Python', 'C', 'C++', 'Java', 'PHP', 'R']
Python C C++ Java PHP R

2.5.2 字符串的聚合——“聚合字符”.join(可迭代数据类型)

  • 可迭代类型 如:字符串、列表
s = "12345"
s_join = ",".join(s) #Take each of the iterable objects out,Add aggregate characters between two adjacent ones
s_join
'1,2,3,4,5'
  • Elements of sequence type must be of type character
# s = [1, 2, 3, 4, 5] Aggregation cannot be used
s = ["1", "2", "3", "4", "5"]
"*".join(s)
'1*2*3*4*5'

3.5.3 删除两端特定字符——字符串.strip(删除字符)

  • stripSearch from both sides,The specified character is encountered to delete it,A non-specified character was encountered,搜索停止
  • Similar to left deletelstripand right deleterstrip
s = " I have many blanks "
print(s.strip(" ")) #Search from both ends,Remove spaces after the specified character is encountered,然后停止
print(s.lstrip(" "))
print(s.rstrip(" "))
print(s)
I have many blanks
I have many blanks
I have many blanks
I have many blanks

3.5.4 字符串的替换——字符串.replace(“被替换”,“替换成”)

s = "Python is coming"
s1 = s.replace("Python","Py")
print(s1)
Py is coming

3.5.5 字符串统计——字符串.count(“待统计字符串”)

s = "Python is an excellent language"
print("an:", s.count("an"))
print("e:", s.count("e"))
an: 2
e: 4

3.3.6 字符串字母大小写

  • 字符串.upper() 字母全部大写
s = "Python"
s.upper()
'PYTHON'
  • 字符串.lower() 字母全部小写
print(s.lower())
print(s)
python
Python
  • 字符串.title()首字母大写
s.title()
'Python'

第三部分 布尔类型 TRUE or False

image-20220908152026507

3.1 逻辑运算的结果

a = 10
print(a > 8)
print(a == 12)
print(a < 5)
True
False
False
  • any() One of the data is non-zeroTrue
  • all() One of the data is zeroFalse (The elements are all non-zero)
print(any([False,1,0,None])) # 0 False None 都是无
print(all([False,1,0,None]))
True
False

3.2 指示条件

n = 2800
while True:
m = eval(input("请输入一个正整数:"))
if m == n:
print("正确")
break
elif m > n:
print("太大了")
else:
print("太小了")
请输入一个正整数:280
太小了
请输入一个正整数:2800
正确

3.3 作为numpy数组的掩码

import numpy as np
x = np.array([[1, 3, 2, 5, 7]]) # 定义 numpy数组
print(x > 3)
x[x > 3]
[[False False False True True]]
array([5, 7])

第四部分 类型判别及类型转换

image-20220908152036300

4.1 类型判别

  • type(变量)
age = 20
name = "Ada"
print(type(age))
print(type(name))
<class 'int'>
<class 'str'>
  • isinstance(变量,预判类型) 承认继承
  • The variable type is a subtype of the predicated type,则为真,否则为假
print(isinstance(age, int)) # 承认继承 这里的intIt's like a class
True
print(isinstance(age, object))
print(isinstance(name, object)) # object 是所有类的老祖宗
True
True
  • 字符串检查方法

字符串.isdigit()字符是否只有数字组成

age = "20"
name = "Ada"
age.isdigit()
True
name.isdigit()
False

字符串.isalpha()字符是否只有字母组成

name.isalpha()
True
age.isalpha()
False

字符串.isalnum()字符是否只有数字和字母组成

"Ada20".isalnum() # For example, it can be used to determine whether the user name is legal
True

4.2 类型转换

  • 数字类型转字符串 str(数字类型)
age = 20
print("My age is "+str(age))
My age is 20
  • Convert a string consisting of only numbers to numbers int() float() eval()
s1 = "20"
s2 = "10.1"
int(s1) # Integer only
# int(s2) 会错误
20
float(s1)
20.0
float(s2)
10.1
eval(s1)
20
eval(s2)
10.1
版权声明:本文为[timerring]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/252/202209090305309958.html