Python 来自...Go
基础知识第一部分
介绍
What is programming?
简单来说,编程就是我们给计算机下达指令的一种方式。“给它一份说明书,计算机就会照做”。
事实上,计算机不懂英语或任何其他人类语言。计算机用 1 和 0 来表达信息;例如“开”或“关”(所有其他电子元件也是如此)。
但对于人类来说,用 1 或 0 来交流会显得杂乱无章,甚至相当困难。因此,人类开发出了介于人类语言和机器语言(0/1)之间的编程语言。
有些编程语言是低级的(更接近机器语言),而有些则是高级的(更接近人类语言)。
低级编程语言的例子包括:
- 集会
高级编程语言的示例包括:
- Python
- JavaScript
那么什么是programming language
?
编程语言是将字符串或图形程序元素转换为各种机器代码输出(计算机可以理解)的规则集。
Note:
归根结底,所有编程语言都做同一件事:告诉机器该做什么。然而,不同的语言有不同的执行模式。
其妙之处在于“大多数语言都有非常相似的原则”。
最困难的部分只是学习第一语言。
在编程语言和机器语言之间,我们需要一个“翻译器”,它既能理解编程语言(源代码),又能理解机器语言,这样才能把我们的代码翻译成机器语言,让计算机理解。*The translator ain't a person
而另一个程序,既可以是解释器,也可以是编译器。
像翻译器一样,解释器逐行执行代码,并在机器上执行代码。相反,编译器会一次性读取整个文件,然后将其翻译成机器码。(它们之间的其他主要区别有些复杂,超出了本课程的范围)
Python 通常使用解释器,因此要使用 Python,您必须下载解释器。
Note:
要学习或了解以下任何主题的更多信息,请参阅以下 Python 官方文档的链接。
Python解释器
要下载 python 解释器,我们首先访问python.org。
在“下载”下,根据操作系统选择“Windows”或“Mac OS”。(系统会自动检测您电脑的配置,并根据您使用的 Windows 操作系统,建议选择 32 位或 64 位版本。)
下载完成后,点击加载安装程序。
注意:安装时,请记得勾选“将 Python 添加到 PATH”选项,如下所示:
单击“立即安装”后,安装将立即开始:
...安装成功后,程序将通知您:
安装 Python 后,您可以使用终端(在 Windows 上)使用命令提示符或 PowerShell 来确认 Python 是否已成功添加到 PATH 环境变量中。
“打开命令提示符或 PowerShell,输入‘python’,然后点击‘Enter’运行命令”。
为了确保 Python 安装成功并添加到 PATH 环境变量中,运行“python”后,命令提示符(Image1)和 PowerShell(Image2)都应该如下图所示:
...但很可能在安装或添加到 PATH 时出现问题,运行“python”命令后,它将返回错误,但可以重新安装解释器并记得检查“将 Python 添加到 PATH”。
第一个“Hello World”程序
设置好解释器后,我们可以使用终端(命令提示符、GIT Bash、PowerShell、Termux 等)运行一些 Python 命令。
打开终端,首先运行“python”命令。然后,使用 Python 命令“print”显示字符。
>>> print("I am using python")
I am using python
设置环境(IDE 设置)
我们之前也只是运行过第一个 Python 程序,但专业上不可能把整个公司的程序都跑在终端上,主要是用来快速测试。
一般情况下,我们会用代码编辑器或者 IDE 来运行 Python 程序。
为什么不在 Word 文档或文本文件中编写代码?
在 Word 文档中,代码将以文本形式呈现,因此如果出现语法错误,将不会返回任何信息。此外,专业开发人员需要代码编辑器和 IDE 提供的一些额外工具来帮助他们更高效地编写代码。
What is a code editor and an IDE, and what is their difference?
代码编辑器轻量级,并提供自动完成等功能;而 IDE 则是功能齐全的环境,提供一系列额外功能,如调试、自动完成、代码格式化、代码片段等。
最流行的 Python 代码编辑器和 IDE 包括:Sublime Text、Visual Studio Code、PyCharm 和 Jupyter Notebooks。
-
安装、设置、自定义和使用 Sublime Text:链接
-
要安装、设置、自定义和使用 Visual Studio Code:链接
-
要安装、设置、自定义和使用 PyCharm:链接
-
安装、设置、自定义和使用 Jupyter Notebook:链接
Python 基础
对于任何程序员来说,为了学习一门语言,他们真正需要掌握 4 个关键的东西:
i)。语言术语 - 语言中使用不同的词汇和定义,例如变量、语句和实例。ii
)。语言数据类型 - 整数、字符串等。iii
)。操作 - 使用内存并执行某些操作。iv
)。编写语言的最佳实践。
1.变量
变量是存储程序中可用信息的内存位置。
它们就像存储/保存对象的“容器”
。 它们可以保存用户输入、值等。
例如:
>>> name = "Mark"
>>> print(name)
Mark
Hence, 'name' is a variable that stores the name, Mark.
>>> iq = 190
>>> print(iq)
190
Note:
为变量赋值称为绑定。
声明变量的规则
- 蛇形套
>>> user_iq = 190
- 以小写字母或下划线开头
>>> _useriq = 190
- 字母、数字、下划线
>>> us4er_iq = 190
- 区分大小写
>>> user_iq = 190
>>> user_IQ = 200
>>> print(user_iq)
190
>>> print(user_IQ)
200
- 不要覆盖 python 关键字 -
One cannot assign values to python keywords.
要查找 python 中的完整关键字列表,请单击以下链接。
变量也可以重新分配。
>>> iq = 190
>>> user_age = iq/4
>>> print(user_age)
47.5
Constants
- 这些变量不应改变。
它们以大写字母书写。
>>> PI = 3.14
Dunder Variables
- 以双下划线开头。(课程后面会讲到)
示例:
__debug__
__loader__
__import__
多次为变量赋值:
>>> a, b, c = 1, 2, 3
>>> print(a)
1
>>> print(b)
2
>>> print(c)
3
Note:
变量应该具有描述性。
表达式与语句
>>> iq = 100
>>> user_age = iq / 5
- 表达式是一段产生值的代码。例如:
iq / 5
-
语句是执行某种操作的整行代码。
例如:iq = 100
,user_age = iq / 5
-
增强赋值运算符
>>> some_value = 5
>>> some_value = some_value + 2
>>> print(some_value)
7
(也可以写成)
>>> some_value = 5
>>> some_value += 2
>>> print(some_value)
7
>>> some_value = 5
>>> some_value -= 2
>>> print(some_value)
3
>>> some_value = 5
>>> some_value *= 2
>>> print(some_value)
10
2. Python数据类型
数据类型是一种数据分类,它告诉编译器或解释器程序员如何使用数据。它指定变量具有哪种类型的值,以及可以对其应用哪种类型的数学、关系或逻辑运算而不会导致错误。
在 Python 中,数据类型包括:
- 基本数据类型
-Text Type:
str - string
-Numeric Types:
int - integer
float
complex
-Sequence Types:
list
tuple
range
-Mapping Type:
dict - dictionary
-Set Types:
set
frozenset
-Boolean Type:
bool - boolean
-Binary Types:
bytes
bytearray
memoryview
- 自定义数据类型 - 从类创建
- 专用数据类型 - 来自模块的扩展
- 无类型 -
None
a.) int - 整数
整数是没有小数点的整数;1、2、3、4、456、-4643、-77。
>>> print(2 + 4)
6
>>> print(2 - 4)
-2
>>> print(2 * 4)
8
>>> print(type(2))
<class 'int'>
>>> print(type(-29))
<class 'int'>
>>> print(type(2 + 4))
<class 'int'>
>>> print(type(2 - 4))
<class 'int'>
b.) 浮点数
这些是带有小数点的数字;5.7、8.0、3.5554、0.00003、-0.543、-4.229。
>>> print(2 / 4)
0.5
>>> print(type(2.7))
<class 'float'>
>>> print(type(-27.554))
<class 'float'>
>>> print(type(2.8 + 4))
<class 'float'>
>>> print(type(2 / 4))
<class 'float'>
Note:
- 浮点数比整数占用更多的内存空间。
这是因为数字需要以二进制形式存储在内存中。但是,当数字有小数位时,例如 10.56,由于小数点的存在,很难用二进制形式(0/1)表示,'.'
因此浮点数会存储在两个不同的位置,例如,一个存储 10,另一个存储 56。
要了解有关浮点数的更多信息,这里是有关浮点数的 Python 文档的链接。
- 对整数和浮点数的运算。
operators
+、-、*、/、**、//、%
+ ----- addition
- ----- subtraction
* ----- multiplication
/ ----- division
** ---- ‘的力量’
例如。
>>> print(2 ** 4)
16
>>> print(7 ** 9)
40,353,607
// ---- '将商向下舍入为最接近的整数'
例如。
>>> print(2 // 4)
0
>>> print(3 // 4)
0
>>> print(4 // 4)
1
>>> print(5 // 4)
1
>>> print(7 // 4)
1
>>> print(9 // 4)
2
% ---- '返回余数'
例如。
>>> print(5 % 4)
1
>>> print(5 % 2)
1
>>> print(5 % 3)
2
- 数学函数(对整数和浮点数执行的操作)。
i) 四舍五入 - 将数字四舍五入为最接近的整数。
>>> print(round(3.1))
3
>>> print(round(3.9))
4
ii) abs - 返回参数的绝对值。
>>> print(abs(-20))
20
>>> print(abs(-354))
354
>>> print(abs(44))
44
iii) pow - 用于计算一个数的特定幂。
>>> print(pow(2,3))
8
>>> print(pow(4,3))
64
iv) max - 返回最高数字。
>>> print(max(2,3))
3
>>> print(max(2,-9))
2
v) min - 返回最小的数字。
>>> print(min(3,8))
3
>>> print(min(2,-9))
-9
对于大多数其他数学函数,必须从 math 模块“导入”。from math import *
* 符号表示“全部”,因此我们从 math 模块导入所有函数。
i) floor——向下舍入该数字。
>>> from math import *
>>> print(floor(3.7))
3
>>> print(floor(5.9))
5
ii) ceil – 将数字向上舍入。
>>> from math import *
>>> print(ceil(3.2))
4
>>> print(ceil(5.9))
5
>>> print(ceil(5.3))
5
iii) sqrt - 返回数字的平方根
>>> from math import *
>>> print(sqrt(4))
2.0
>>> print(sqrt(9))
3.0
>>> print(sqrt(121))
11.0
To get more mathematical functions used in python,
点击以下链接。
- 运算符优先级 (BODMAS)
B - 括号
O - 关机
D - 除法
M - 乘法
A - 加法
S - 减法
>>> print(20 - 3 * 4)
8
>>> print((20 - 3) * 4)
68
>>> print((20 - 3) + 2 ** 2)
21
- 转换为二进制*
optional
>>> print(bin(5))
0b101
>>> print(int('0b101', 2))
5
c.) str - 字符串
字符串是一段文本。它可以用双引号或单引号书写。
>>> greetings = "hi, hello there!"
>>> print(greetings)
hi, hello there!
>>> greetings = 'Welcome!'
>>> print(greetings)
Welcome!
>>> print(type("hi, hello there!"))
<class 'str'>
对于长字符串/句子(包含很多行的字符串),我们使用三重引号:
>>> passage = ''' Mark Gatere is a student.
He is currently at University pursuing his degree program.
He wants to become a Data Scientist in future.'''
>>> print(passage)
Mark Gatere is a student.
He is currently at University pursuing his degree program.
He wants to become a Data Scientist in future.
- 使用字符串
字符串连接
连接是将一系列事物连接在一起的动作,因此,字符串连接是将多个字符串串联成一个字符串。
>>> first_name = "Mark"
>>> second_name = "Gatere"
>>> full_name = first_name + second_name
>>> print(full_name)
MarkGatere
>>> first_name = "Mark"
>>> second_name = "Gatere"
>>> full_name = first_name + ' ' + second_name
>>> print(full_name)
Mark Gatere
类型转换
这是将值从一种数据类型转换为另一种数据类型。
>>> print(type(str(100)))
<class 'str'>
>>> a = str(100)
>>> b = int(a)
>>> a_type = type(a)
>>> b_type = type(b)
>>> print(a_type)
<class 'str'>
>>> print(b_type)
<class 'int'>
转义序列
我们使用反斜杠。
>>> weather = 'It\'s sunny'
>>> print(weather)
It's sunny
>>> weather = "It's \"kind of\" sunny"
>>> print(weather)
It's "kind of" sunny
>>> weather = 'It\\s sunny'
>>> print(weather)
It\s sunny
\t 用于在输出中添加制表符。
>>> weather = '\t It\'s sunny'
>>> print(weather)
It's sunny
\n 用于将其后的部分移至新行。
>>> weather = "It's sunny \n hope you have a good day."
>>> print(weather)
It's sunny
hope you have a good day
格式化字符串(f 字符串)
在预期输出的开头添加“f”。
>>> name = "Johnny"
>>> age = 55
>>> print ("hi" + name + ". You are" + str(age) + "years old.")
hi Johnny. You are 55 years old.
(can also be written as)
>>> name = "Johnny"
>>> age = 55
>>> print (f"hi {name}. You are {age} years old.")
hi Johnny. You are 55 years old.
在 Python 2 中(但也适用于 Python 3):
>>> name = "Johnny"
>>> age = 55
>>> print ("hi {}. You are {} years old.".format(name, age))
hi Johnny. You are 55 years old.
>>> name = "Johnny"
>>> age = 55
>>> print ("hi {1}. You are {0} years old.".format(name, age))
hi 55. You are Johnny years old.
字符串索引
字符串以有序的字符形式存储在内存中。
my name is
0123456789
要访问字符串中的每个字符,我们使用索引。索引从零(0)开始。
>>> sentence = "my name is Mark"
>>> print(sentence[3])
n
>>> sentence = "my name is Mark"
>>> print(sentence[8])
i
字符串切片
[start:stop] - 我们从指定的索引开始,但停止在给定的索引处,但不包括给定的索引。
>>> number = '01234567'
>>> print(number[0:7])
0123456
>>> number = '01234567'
>>> print(number[0:8])
01234567
>>> sentence = "my name is Mark"
>>> print(sentence[1:10])
y name is
[开始:停止:跨步]
>>> number = '01234567'
>>> print(number[0:8:2])
0246
>>> sentence = "my name is Mark"
>>> print(sentence[1:15:2])
ynm sMr
使用索引访问值的额外方法:
>>> number = '01234567'
>>> print(number[1:])
1234567
>>> number = '01234567'
>>> print(number[:5])
01234
>>> number = '01234567'
>>> print(number[::2])
0246
>>> number = '01234567'
>>> print(number[-1])
7
>>> number = '01234567'
>>> print(number[-2])
6
>>> number = '01234567'
>>> print(number[-3])
5
>>> number = '01234567'
>>> print(number[::-1])
76543210
>>> number = '01234567'
>>> print(number[::-2])
7531
不变性
Python 中的字符串是不可变的(它们不能被改变)。
内置字符串函数和方法
len() - 用于查找字符串中的字符数。
>>> greet = "Hello"
>>> print(len(greet))
5
x.upper() - 将整个字符串大写或更改为大写。
>>> greet = "Hello"
>>> print(greet.upper)
HELLO
x.lower() - 将整个字符串更改为小写。
>>> greet = "HELLO"
>>> print(greet.lower)
hello
x.capitalize() - 将字符串开头的第一个字符大写。
>>> greet = "hello"
>>> print(greet.capitalize)
Hello
x.isupper() - 根据字符串是否为大写返回 True 或 False。
x.islower() - 根据字符串是否为小写返回 True 或 False。
- 结合使用各种功能。
>>> phrase = "My name is Mark"
>>> print(phrase.upper().isupper())
True
x.find() - 返回您在字符串中查找的字符的索引。
>>> quote = "to be or not to be"
>>> print(quote.find("be"))
3
x.replace() - 用于用新字符替换字符串中的字符。
>>> quote = "to be or not to be"
>>> print(quote.replace("be", "me"))
to me or not to me
>>> quote = "to be or not to be"
>>> print(quote.replace("t", "y"))
yo be or noy yo be
x.index - 返回特定字符的索引或字符开始的索引。
>>> greet = "hello"
>>> print(greet.index("e"))
1
>>> greet = "hello"
>>> print(greet.index("l"))
2
>>> greet = "hello"
>>> print(greet.index("lo"))
3
To learn more on string methods,
点击以下链接
d.) bool - 布尔值
此数据类型由 True 或 False 组成。
>>> is_cool = True
>>> print(is_cool)
True
>>> is_tall = False
>>> print(is_tall)
False
>>> print(bool(1))
True
>>> print(bool(0))
False
>>> print(bool('True'))
True
>>> print(bool('False'))
True
>>> print(bool())
False
Note:
只要有值,布尔值始终为 True。如上例所示,0 或空数据将始终返回 False。
在学习更多数据类型之前,需要学习的一个重要概念是——获取用户的输入。
您遇到了一个需要填写的表单。
该表单通常为空白,每个部分都需要填写具体的详细信息,包括姓名、电子邮件地址和联系方式。示例如下:
在 Python 中,我们还会创建需要用户输入的程序,从而允许程序的用户向程序中输入信息。为了创建这些程序,我们使用关键字 ,input
它告诉解释器我们需要用户输入才能继续执行其他命令。

Note:
默认情况下,用户的每个输入都存储为字符串(包括数字),因此对于任何数学计算,输入都必须转换为数字,即整数或浮点数。
>>> birth_year = input("What year were you born? ")
>>> age = 2022 - birth_year
>>> print(f"Your age is: {age} years old")
What year were you born? _2001_
#Will return an error as birth_year(string) cannot
be subtracted from 2022(integer).
>>> birth_year = input("What year were you born? ")
>>> age = 2022 - int(birth_year)
>>> print(f"Your age is: {age} years old")
What year were you born? _2001_
Your age is: 21 years old
练习 1(如下所示)
创建一个简单的计算器,要求用户输入两个数字,找到它们的总和并输出总和。
(Note the two different programs)
>>> num1 = input("Enter a number: ")
>>> num2 = input("Enter a second number: ")
>>> sum = num1 + num2
>>> print(sum)
Enter a number: _12_
Enter a second number: _5.2_
125.2
# Correct Program
>>> num1 = input("Enter a number: ")
>>> num2 = input("Enter a second number: ")
>>> sum = int(num1) + int(num2)
>>> print(sum)
Enter a number: _12_
Enter a second number: _5.2_
17.2
练习 2(如下所示)
创建一个简单的密码检查器,以隐藏格式输出密码并输出密码中的字符数。
>>> user_name = input("Enter your username: ")
>>> password = input("Enter your Password: ")
>>> pass_length = len(password)
>>> pass_hidden = 'x' * pass_length
>>> print(f"Hello {user_name}, your password: {pass_hidden} is {pass_length} characters long.")
Enter your username: _gateremark_
Enter your Password: _swddbb243tbfbd_
Hello gateremark, your password: xxxxxxxxxxxxxx is 14 characters long.

让我们开始下一个数据类型:
e.) 列表
列表是任意类型对象的有序序列。它用方括号 [] 表示。
它可以包含不同数据类型的项目集合,有时也可以称为数组,尽管列表和数组之间略有不同。(本课程稍后会介绍这一点)。
>>> li = [1, 2, 3, 4, 5]
>>> li2 = ['a', 'b', 'c', 'f']
>>> li3 = [1, 2, 'r', 'u', True]
>>> print(li)
>>> print(li2)
>>> print(li3)
[1, 2, 3, 4, 5]
['a', 'b', 'c', 'f']
[1, 2, 'r', 'u', True]
列表是一种数据结构。
数据结构是一种数据组织、管理和存储格式,可以实现高效的访问和修改。
- 访问列表中的单个项目(使用索引)
>>> li3 = [1, 2, 'r', 'u', True]
>>> print(li3[2])
>>> print(li3[4])
r
True
>>> amazon_cart = ["notebooks", "sunglasses", "earphones"]
>>> print(amazon_cart[2])
earphones
>>> amazon_cart = ["notebooks", "sunglasses", "earphones"]
>>> print(amazon_cart[3])
#Returns an error for the index is out range.
- 列表切片
正如我们在字符串中所做的那样,我们可以使用索引 [start:stop] 来访问列表中特定范围的项目。Remember
例如。 [1:7] 选择从索引 1 到索引 7 中的所有项目,但不包括索引 7 中的项目,因此最后一项是索引 6 中的项目。
>>> amazon_cart = ["notebooks",
"sunglasses",
"earphones",
"toys",
"grapes"]
>>> print(amazon_cart[0:4])
['notebooks', 'sunglasses', 'earphones', 'toys']
[开始:停止:跨步]
>>> amazon_cart = ["notebooks",
"sunglasses",
"earphones",
"toys",
"grapes"]
>>> print(amazon_cart[::2])
['notebooks', 'earphones', 'grapes']
- 修改列表中的元素
与字符串不同,列表是可变的,因此可以修改列表中的元素。
>>> amazon_cart = ["notebooks",
"sunglasses",
"earphones",
"toys",
"grapes"]
>>> amazon_cart[0] = "Laptop"
>>> print(amazon_cart)
['Laptop', 'sunglasses', 'earphones', 'toys', 'grapes']
>>> amazon_cart = ["notebooks",
"sunglasses",
"earphones",
"toys",
"grapes"]
>>> amazon_cart[0] = "Laptop"
>>> new_cart = amazon_cart[0:3]
>>> new_cart[1] = "gum"
>>> print(new_cart)
>>> print(amazon_cart)
['Laptop', 'gum', 'earphones']
['Laptop', 'sunglasses', 'earphones', 'toys', 'grapes']
Note:
当你将一个列表赋值给另一个变量时,它会指向原始列表的内存位置,因此,在新变量中修改列表会导致在前一个变量中修改原始列表。
例如:
>>> amazon_cart = ["notebooks",
"sunglasses",
"earphones",
"toys",
"grapes"]
>>> amazon_cart[0] = "Laptop"
>>> new_cart = amazon_cart
>>> new_cart[0] = "gum"
>>> print(new_cart)
>>> print(amazon_cart)
['gum', 'sunglasses', 'earphones', 'toys', 'grapes']
['gum', 'sunglasses', 'earphones', 'toys', 'grapes']
为了避免在修改新变量中分配的列表后修改原始列表,我们在列表变量后使用 [:] 复制整个列表并将其作为新列表存储在不同的变量中。
>>> amazon_cart = ["notebooks",
"sunglasses",
"earphones",
"toys",
"grapes"]
>>> amazon_cart[0] = "Laptop"
>>> new_cart = amazon_cart[:]
>>> new_cart[0] = "gum"
>>> print(new_cart)
>>> print(amazon_cart)
['gum', 'sunglasses', 'earphones', 'toys', 'grapes']
['Laptop', 'sunglasses', 'earphones', 'toys', 'grapes']
- 矩阵(这些是多维列表/数组)
>>> matrix = [
[2, 4, 6],
[9, 5, 7],
[3, 8, 1]
]
>>> print(matrix)
[[2, 4, 6], [9, 5, 7], [3, 8, 1]]
访问多维列表/数组中的元素。
>>> matrix = [
[2, 4, 6],
[9, 5, 7],
[3, 8, 1]
]
>>> print(matrix[1][2])
>>> print(matrix[0][1])
7
4
>>> matrix = [
[2, 4, 6],
[9, 5, 7],
[3, 8, 1]
]
>>> print(matrix[2][3])
#Returns an error for the index is out of range.
- 列出函数和方法/操作
len() - 查找列表的长度(列表中的项目数)。
>>> basket = [1, 2, 3, 4, 5]
>>> print(len(basket))
5
x.append() - 用于向原始列表添加值。它会就地
修改列表,因此不会创建原始列表的副本。
>>> basket = [1, 2, 3, 4, 5]
>>> basket.append(100)
>>> print(basket)
[1, 2, 3, 4, 5, 100]
>>> basket = [1, 2, 3, 4, 5]
>>> new_list = basket.append(100)
>>> print(basket)
>>> print(new_list)
[1, 2, 3, 4, 5, 100]
None
>>> basket = [1, 2, 3, 4, 5]
>>> basket.append(100)
>>> new_list = basket
>>> print(basket)
>>> print(new_list)
[1, 2, 3, 4, 5, 100]
[1, 2, 3, 4, 5, 100]
x.insert() - 用于在列表中特定索引的任意位置插入值。它也会就地
修改列表,因此不会创建原始列表的副本。
>>> basket = [1, 2, 3, 4, 5]
>>> new_list = basket.insert(4, 100)
>>> print(basket)
>>> print(new_list)
[1, 2, 3, 4, 100, 5]
None
>>> basket = [1, 2, 3, 4, 5]
>>> basket.insert(4, 100)
>>> new_list = basket
>>> print(basket)
>>> print(new_list)
[1, 2, 3, 4, 100, 5]
[1, 2, 3, 4, 100, 5]
x.extend() - 用于将另一个列表附加到原始列表。它也会就地
修改列表,因此不会创建原始列表的副本。
>>> basket = [1, 2, 3, 4, 5]
>>> new_list = basket.extend([100, 101, 107])
>>> print(basket)
>>> print(new_list)
[1, 2, 3, 4, 5, 100, 101, 107]
None
>>> basket = [1, 2, 3, 4, 5]
>>> basket.extend([100, 101, 107])
>>> new_list = basket
>>> print(basket)
>>> print(new_list)
[1, 2, 3, 4, 5, 100, 101, 107]
[1, 2, 3, 4, 5, 100, 101, 107]
numbers = [1, 2, 3, 4]
friends = ["Kelvin", "Karen", "Jim"]
friends.extend(numbers)
print(friends)
['Kelvin', 'Karen', 'Jim', 1, 2, 3, 4]
x.pop() - 自动从列表或给定索引处移除(弹出)最后一个元素。返回被弹出的元素。
>>> basket = [1, 2, 3, 4, 5]
>>> basket.pop()
>>> print(basket)
[1, 2, 3, 4]
>>> friends = ["Kelvin", "Karen", "Jim"]
>>> friends.pop()
>>> print(friends)
['Kelvin', 'Karen']
>>> basket = [1, 2, 3, 4, 5]
>>> basket.pop(0)
>>> print(basket)
[2, 3, 4, 5]
>>> basket = [1, 2, 3, 4, 5]
>>> basket.pop(2)
>>> print(basket)
[1, 2, 4, 5]
>>> basket = [1, 2, 3, 4, 5]
>>> new_list = basket.pop(4)
>>> print(new_list)
5
x.remove() - 从列表中删除一个元素/值。“就地”操作。
>>> basket = [1, 2, 3, 4, 5]
>>> basket.remove(4)
>>> print(basket)
[1, 2, 3, 5]
x.clear() - 清除整个列表。“就地”工作。
>>> basket = [1, 2, 3, 4, 5]
>>> basket.clear()
>>> print(basket)
[]
x.index() - 用于检查列表中元素的索引。
>>> basket = ['a', 'b', 'c', 'd', 'e']
>>> print(basket.index('d'))
3
Checking from a specific index in the list.
>>> basket = ['a', 'b', 'c', 'd', 'e']
>>> print(basket.index('d', 0, 3)) #Checking from index 0 to index 3 (but not including index 3).
#returns an error as 'd' is in index 3 yet index 3 is not included in the range.
- 判断某个元素是否在列表中。
我们使用关键字“in”,它返回 True 或 False。
>>> basket = ['a', 'b', 'c', 'd', 'e']
>>> print('d' in basket)
True
>>> basket = ['a', 'b', 'c', 'd', 'e']
>>> print('i' in basket)
False
>>> print('a' in 'My name is Mark')
True
>>> print('z' in 'What is the time?')
False
x.count() - 用于计算元素在列表中出现的项目数。
>>> basket = ['a', 'b', 'c', 'd', 'e']
>>> print(basket.count('d'))
1
>>> basket = [1, 2, 3, 4, 2, 5, 2]
>>> print(basket.count(2))
3
x.sort() - 用于按升序对列表进行排序。如果列表包含姓名,则按字母顺序排序。“就地”操作。
>>> basket = [5, 2, 3, 4, 1, 3, 2]
>>> basket.sort()
>>> print(basket)
[1, 2, 2, 3, 3, 4, 5]
>>> friends = ["Karen", "Toby", "Elijah"]
>>> friends.sort()
>>> print(friends)
['Elijah', 'Karen', 'Toby']
sorted() - 用于按升序对列表进行排序。如果列表包含姓名,则按字母顺序排序。与方法 x.sort() 不同,sorted() 是一个生成新数组的函数,因此不能就地执行。
>>> friends = ["Karen", "Toby", "Elijah"]
>>> print(sorted(friends))
['Elijah', 'Karen', 'Toby']
>>> basket = [5, 2, 3, 4, 1, 3, 2]
>>> print(sorted(basket))
[1, 2, 2, 3, 3, 4, 5]
x.copy() - 与 [:] 的工作方式相同,通过复制整个列表并创建与原始列表完全相同的新列表。
>>> friends = ["Karen", "Toby", "Elijah"]
>>> new_friends = friends.copy()
>>> print(new_friends)
['Karen', 'Toby', 'Elijah']
x.reverse() - 用于将列表中的元素从最后一个索引的元素反转为第一个索引的元素。“就地”操作。
(它不遵循升序或任何顺序;它只是交换元素)。
>>> friends = ["Karen", "Toby", "Elijah"]
>>> friends.reverse()
>>> print(friends)
['Elijah', 'Toby', 'Karen']
>>> numbers = [1, 5, 3, 8, 7]
>>> numbers.reverse()
>>> print(numbers)
[7, 8, 3, 5, 1]
>>> numbers = [1, 5, 3, 8, 7]
>>> numbers.sort()
>>> numbers.reverse()
>>> print(numbers)
[8, 7, 5, 3, 1]
- 常见列表模式
使用列表切片来反转列表
这将从原始列表创建一个新列表,也就是说,它不能就地工作。
>>> numbers = [1, 5, 3, 8, 7]
>>> numbers.sort()
>>> numbers.reverse()
>>> print(numbers)
>>> print(numbers[::-1])
[8, 7, 5, 3, 1]
[1, 3, 5, 7, 8]
Note:
您可以使用列表切片(-1)或使用 x.reverse() 方法来反转列表,如上所示。
range() - 生成从所述数字到但不包括所述最后一个数字的数字列表。
>>> print (list(range(1, 50)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49]
>>> print (list(range(50)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49]
>>> print (list(range(51)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49,
50]
- 获取列表的长度- 列表中的项目数。
>>> basket = [1, 2, 6, 8, 4, 0]
>>> print(len(basket))
6
>>> names = ["Mark", "Enoch", "Vivian", "Yvonne", "Mercy"]
>>> print(len(names))
5
.join
这是一个字符串方法,用于根据给定的“字符”连接列表中的项目。它会创建一个新项目,因此无法直接执行。
>>> sentence = '!'
>>> new_sentence = sentence.join(['hi', 'my', 'name', 'is', 'JOJO'])
>>> print(new_sentence)
hi!my!name!is!JOJO
>>> sentence = '.'
>>> new_sentence = sentence.join(['hi', 'my', 'name', 'is', 'JOJO'])
>>> print(new_sentence)
hi.my.name.is.JOJO
>>> sentence = ' '
>>> sen2 = ['hello', 'welcome', 'to', 'the', 'city']
>>> new_sentence = sentence.join(sen2)
>>> print(new_sentence)
hello welcome to the city
>>> new_sentence = '!'.join(['hi', 'my', 'name', 'is', 'JOJO'])
>>> print(new_sentence)
hi!my!name!is!JOJO
>>> new_sentence = ' '.join(['hi', 'my', 'name', 'is', 'JOJO'])
>>> print(new_sentence)
hi my name is JOJO
- 列表解包
这是为列表中的每个项目分配一个变量。工作原理类似于在变量中多次赋值。
>>> a,b,c = [1, 2, 3]
>>> print(a)
>>> print(b)
>>> print(c)
1
2
3
在列表解包中,您可以添加更多值,解包赋给变量的值,然后将剩余项存储在各自的变量中。只需添加 * 符号和变量名称即可。
>>> a,b,c *other = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(a)
>>> print(b)
>>> print(c)
>>> print(other)
1
2
3
[4, 5, 6, 7, 8, 9]
>>> a,b,c, *other, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(a)
>>> print(b)
>>> print(c)
>>> print(other)
>>> print(d)
1
2
3
[4, 5, 6, 7, 8]
9
f.) 无类型
这是一种表示不存在值的特殊数据类型。
>>> weapons = None
>>> print(weapons)
None
g.) 元组 元
组类似于列表,但却是不可变的数据类型。存储在元组中的数据永远无法更改,例如坐标。
-
无法向其中添加元素。
-
无法从中删除元素。
-
无法修改其中的元素。
元组也是一种数据结构,
它使用括号“()”来存储数据,并且可以在一个元组中存储不同类型的数据。
>>> my_tuple = (1, 2, 4, 7, 5)
>>> print(my_tuple)
(1, 2, 4, 7, 5)
>>> my_tuple = (1, 2, 'a', True)
>>> print (my_tuple)
(1, 2, 'a', True)
>>> my_tuple = (1, 2, 4, 7, 5)
>>> print(my_tuple[3])
7
>>> my_tuple = (1, 2, 4, 7, 5)
>>> print(3 in my_tuple)
False
>>> my_tuple = (1, 2, 4, 7, 5)
>>> print(5 in my_tuple)
True
>>> my_tuple = (1, 2, 4, 7, 5)
>>> my_tuple[3] = 9
>>> print(my_tuple)
#returns an error as tuples cannot be modified
- 元组可以切片(类似于列表切片)
>>> my_tuple = (1, 2, 3, 4, 5)
>>> new_tuple = my_tuple[1:4]
>>> print(new_tuple)
(2, 3, 4)
>>> my_tuple = (1, 2, 3, 4, 5)
>>> new_tuple = my_tuple[1:2]
>>> print(new_tuple)
(2,)
>>> x, y, z, *other = (1, 2, 3, 4, 5)
>>> print(x)
>>> print(y)
>>> print(z)
>>> print(other)
1
2
3
[4, 5]
元组有两种主要方法:
-
x.count()
-
x.索引()
>>> my_tuple = (1, 5, 3, 4, 5)
>>> print(my_tuple.count(5))
2
>>> my_tuple = (1, 5, 3, 4, 5)
>>> print(my_tuple.index(4))
3
- 获取元组的长度:
>>> my_tuple = (1, 5, 3, 4, 5)
>>> print(len(my_tuple))
5
- 元组列表:
>>> coordinates = [(4, 5), (6, 7), (80, 34)]
>>> print(coordinates)
[(4, 5), (6, 7), (80, 34)]
>>> coordinates = [(4, 5), (6, 7), (80, 34)]
>>> print(coordinates[1])
(6, 7)
>>> coordinates = [(4, 5), (6, 7), (80, 34)]
>>> print(coordinates[1][1])
7
h.) 字典
这是一种特殊的数据结构,允许以无序的键值对形式组织或存储数据。它使用花括号“{}”。
dictionary = {
'key' : value,
'key' : value
}
键必须始终唯一(不应重复)。
要访问值,我们使用键。
>>> my_dict = {
'a' : 1,
'b' : 2,
'x' : 4
}
>>> print(my_dict)
{'a': 1, 'b': 2, 'x': 3}
>>> my_dict = {
'a' : 1,
'b' : 2,
'x' : 4
}
>>> print(my_dict['b'])
2
>>> my_dict = {
'a' : 1,
'b' : 2
'x' : 4
}
>>> print(my_dict['c'])
#returns an error for the key is not defined.
Note:
字典中的元素存储在不同的内存位置,这些位置不一定按顺序排列:
>>> my_dict = {
'a' : 1,
'b' : 2,
'x' : 4
}
>>> print(my_dict)
{'a': 1, 'b': 2, 'x': 3}
At times the output may be as shown below.
>>> my_dict = {
'a' : 1,
'b' : 2,
'x' : 4
}
>>> print(my_dict)
{'x': 4, 'a': 1, 'b': 2}
字典键可以存储不同数据类型的值(与列表和元组相同)。
>>> my_dict = {
'a' : [1, 2, 3],
'b' : "hello",
'x' : True,
't' : 5
}
>>> print(my_dict)
{'a': [1, 2, 3], 'b': 'hello', 'x': True, 't': 5}
>>> my_dict = {
'a' : [1, 2, 3],
'b' : "hello",
'x' : True,
't' : 5
}
>>> print(my_dict['a'])
[1, 2, 3]
>>> my_dict = {
'a' : [1, 2, 3],
'b' : "hello",
'x' : True,
't' : 5
}
>>> print(my_dict['a'][1])
2
>>> my_dict = {
'a' : [1, 2, 3],
'b' : "hello",
'x' : True,
't' : 5
}
>>> print(my_dict['b'][4])
o
- 列表中的字典。
>>> my_list = [
{
'a' : [1, 2, 3],
'b' : "hello",
'x' : True,
't' : 5
},
{
'a' : [4, 5, 6],
'b' : "welcome",
'x' : False,
't' : 5
}
]
>>> print(my_list[0]['a'][2])
3
- 字典键
字典的键是不可变类型,并且应该是唯一的。这意味着字符串、数字、元组和布尔值可以作为键,而列表则不能。Note:
当将键重新赋值给另一个值时,键中的原始值将被覆盖。
>>> dictionary = {
123 : [1, 2, 5, 6],
True : 'hello',
'a' : ('a', 't', 'u'),
[100] : False
}
>>> print (dictionary[100])
#returns an error as a list is mutable and hence cannot be used as a key.
>>> dictionary = {
'123' : [1, 2, 5, 6],
True : 'hello',
'123' : ('a', 't', 'u')
}
>>> print(dictionary['123'])
('a', 't', 'u')
- 字典方法
x.get() - 用于检查字典中是否存在某个键的方法。有时,如果缺少某个键,它会返回给定的默认值。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print(user.get('age'))
None
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print(user.get('age', 55))
55
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u'),
'age' : 20
}
>>> print(user.get('age', 55))
20
- 创建字典的第二种方法:
通过使用关键字 dict(key = value) 。
键不能是表达式,也就是说,使用 dict 时,它应该是一个变量。
>>> user2 = dict(name = 'John')
>>> print(user2)
{'name': 'John'}
>>> user2 = dict(name = 'John', name2 = 'Mark')
>>> print(user2)
{'name': 'John', 'name2': 'Mark'}
- “in”关键字也可以在字典中使用。
它根据字典中某个键是否存在返回 True 或 False。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print('size' in user)
False
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print('basket' in user)
True
x.keys() - 用于检查字典中是否存在特定键。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print('123' in user.keys())
True
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print('age' in user.keys())
False
x.values() - 用于检查字典中是否存在特定值。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print('hello' in user.values())
True
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print(('a', 't', 'u') in user.values())
True
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print([1, 2, 6, 5] in user.values())
False
x.items() - 以元组的形式返回字典中的所有项目。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print(user.items())
dict_items([('123', [1, 2, 5, 6]), (True, 'hello'), ('basket', ('a', 't', 'u'))])
x.clear() - 清除字典并返回一个空字典。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> print(user.clear())
None
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> user.clear()
>>> print(user)
{}
x.copy() - 创建字典的副本。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u')
}
>>> user2 = user.copy()
>>> print(user2)
{'123': [1, 2, 5, 6], True: 'hello', 'basket': ('a', 't', 'u')}
x.pop() - 从字典中删除键及其值并返回该值。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u'),
'age' : 20
}
>>> user.pop('age')
>>> print(user)
20
{'123': [1, 2, 5, 6], True: 'hello', 'basket': ('a', 't', 'u')}
x.popitem() - 删除一对随机的键值。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u'),
'age' : 20
}
>>> user.popitem()
>>> print(user)
('age', 20)
{'123': [1, 2, 5, 6], True: 'hello', 'basket': ('a', 't', 'u')}
x.update() - 用于更新字典中的键或添加新的键和值。
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u'),
'age' : 20
}
>>> user.update({'age' : 55})
>>> print(user)
{'123': [1, 2, 5, 6], True: 'hello', 'basket': ('a', 't', 'u'), 'age': 55}
>>> user = {
'123' : [1, 2, 5, 6],
True : 'hello',
'basket' : ('a', 't', 'u'),
'age' : 20
}
>>> user.update({'age2' : 55})
>>> print(user)
{'123': [1, 2, 5, 6], True: 'hello', 'basket': ('a', 't', 'u'), 'age': 20, 'age2': 55}
i.) 集合:
这些是唯一对象的无序集合。它使用花括号,并且仅返回唯一对象。
>>> my_set = {1, 2, 3, 4, 5, 5}
>>> print(my_set)
{1, 2, 3, 4, 5}
>>> my_set = {1, 2, 3, 4, 5, 5}
>>> my_set.add(2)
>>> my_set.add(100)
>>> print(my_set)
{1, 2, 3, 4, 5, 100}
>>> my_list = [1, 2, 2, 3, 5, 5]
>>> print(set(my_list))
{1, 2, 3, 5}
集合中的对象未建立索引,因此无法使用索引进行访问。
>>> my_set = {1, 2, 3, 4, 5, 5}
>>> print(my_set[0])
#returns an error as items cannot be accessed using indexes in sets
>>> my_set = {1, 2, 3, 4, 5, 5}
>>> print(1 in my_set)
True
>>> my_set = {1, 2, 3, 4, 5, 5, 7, 7}
>>> print(6 in my_set)
False
>>> my_set = {1, 2, 3, 4, 5, 5, 7, 7}
>>> print(len(my_set))
6
- 将集合转换为列表。
>>> my_set = {1, 2, 3, 4, 5, 5, 7, 7}
>>> print(list(my_set))
[1, 2, 3, 4, 5, 7]
x.copy - 复制一组。
>>> my_set = {1, 2, 3, 4, 5, 5, 7, 7}
>>> new_set = my_set.copy()
>>> my_set.clear()
>>> print(new_set)
>>> print(my_set)
{1, 2, 3, 4, 5, 7}
set()
- 集合中的方法
x.difference() - 找出两个集合的差异。
>>> my_set = {1, 2, 3, 4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.difference(your_set))
{1, 2, 3}
x.discard() - 如果元素是集合成员,则将其从集合中移除。原地操作。
>>> my_set = {1, 2, 3, 4, 5}
>>> my_set.discard(5)
>>> print(my_set)
{1, 2, 3, 4}
x.difference_update() - 从前一个集合中删除另一个集合的所有元素。
>>> my_set = {1, 2, 3, 4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.difference_update(your_set))
{1, 2, 3}
x.intersection() - 返回两个集合中的公共值。
>>> my_set = {1, 2, 3, 4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.intersection(your_set))
{4, 5}
Note:
您还可以使用 & 符号表示交叉点。
>>> my_set = {1, 2, 3, 4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set & your_set)
{4, 5}
x.isdisjoint() - 如果它们具有或不具有共同值,则分别返回 False 或 True。
>>> my_set = {1, 2, 3, 4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.isdisjoint(your_set))
False
>>> my_set = {1, 2, 3}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.isdisjoint(your_set))
True
x.union() - 返回两个集合的并集并删除重复项。
>>> my_set = {1, 2, 3}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.union(your_set))
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Note:
对于联合,您还可以使用 | 符号。
>>> my_set = {1, 2, 3}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set | your_set)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
x.issubset() - 返回 True 或 False,判断一个集合是否是另一个集合的子集。
>>> my_set = {4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.issubset(your_set))
True
x.issuperset() - 返回 True 或 False,判断一个集合是否是另一个集合的超集。
超集与子集相反。
>>> my_set = {4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(my_set.issuperset(your_set))
False
>>> my_set = {4, 5}
>>> your_set = {4, 5, 6, 7, 8, 9, 10}
>>> print(your_set.issuperset(my_set))
True
以下是有关上述主题的更多资源的链接:
恭喜您完成第一个里程碑:Python 基础第一部分。
总结一下,我们学习了 Python 中的变量和数据类型,以及一些 Python 数据结构。
接下来,在Python 基础第二部分中,我们将更深入地学习 Python 的控制结构、循环等等……
鏂囩珷鏉ユ簮锛�https://dev.to/gateremark/python-from-the-word-go-4h93到时候见!