回顾 Python - 基础知识祝你有美好的一天😃!。

2025-06-09

回顾 Python 基础知识

祝你有美好的一天😃!

大家好!祝大家有美好的一天!

我已经有近两个月没有发布任何东西了,因为
我忙于学习和玩游戏,哈哈。好的,我的文章大多是关于JavaScriptTypeScript的,所以我将转到另一个领域,特别是Python。Python是我最喜欢的编程语言不是因为它是现在最流行的编程语言,也不是因为它在软件开发的不同领域有很多用途,比如Web 开发机器学习数据科学,而是因为我用这门语言帮助
我大学毕业。从第一次使用它我就爱上了它。我喜欢它的语法,我喜欢你很容易学习它的基础知识和基本原理,以及与其他语言相比,你可以轻松地用它编写更少的代码。老实说,当我在大学最后一个学期遇到困难时,它给了我希望,我以为自己无法毕业,因为很难安排论文和其他科目之间的时间,但多亏了Python,我毕业了。我已经快两年没有用Python编程了,所以我又开始学习它了,下面是我再次学到的东西。
让我们开始吧。

变量

变量是值的占位符。变量用于在程序中跟踪或记住数据。
我们记住的不是特定的值,而是保存该值的变量。在Python中创建变量非常简单。

my_secret_num = 1
myName = "Mark"
isDone = False
_ = None

# A variable name must not start with a number or a special character except underscore "_"

0_1 = 1 # raises a Syntax Error
dollar$= "$ss" # raises a Syntax Error
@_2 = 1 # raises a Syntax Error

Enter fullscreen mode Exit fullscreen mode

缩进

Python与其他语言的不同之处在于它有严格的缩进规则,有时手动操作非常麻烦,但如果你使用IDE,我认为 IDE 可能有一些选项可以配置要使用的空格数。Python 中使用的标准空格数是4。缩进使你的代码更简洁、更易读。缩进从冒号开始:

if True:
    print("Indentation Rocks") # This statement has 4 spaces before it.

i = 0
while True:
    if i == 2: # This statement has 4 spaces before it.
        break # This statement has 8 spaces before it.
    else:       # This statement has 4 spaces before it.
        i += 1 # This statement has 8 spaces before it.

def func():
    pass  # This statement has 4 spaces before it.

for num in [1,2,3]:
print(num) # This raises an Error SyntaxError: expected an indented block

Enter fullscreen mode Exit fullscreen mode

数据类型

我们赋给变量的每个值都包含一个值,并且该值具有特定的数据类型。每种数据类型都可以在任何情况下使用,但在特定情况或问题中,总有更合适的数据类型可用。Python 有许多数据类型,例如布尔值字符串数字列表字典元组集合文件None

my_first_name = "Mark" # String
my_fav_num = 21 # Number - Integer
my_fav_float_num = 21.0 # Number - Float

is_current_year_odd = False # Boolean - True | False
wish_list = ["new video card","new monitor","new keyboard"]  # List
language_profiencies = { # Dictionary
     "Python" : 6.5,
     "JavaScript" : 8.5
     "TypeScript" : 7
}
cant_change_this = ("Global Warming","is","Real") # Tuple
nums = {1,2,3,4,5,1} # Set
sample_file_data = open("path/to/file.txt","a") # File
Enter fullscreen mode Exit fullscreen mode

操作和流程控制

我们可以在 Python 中使用很多操作。

大部分情况下,它用于使用当前值并更新某个值。我主要使用了此表的前半部分,因为我还没有遇到需要使用后半部分的问题。

增强赋值运算符

速记 相等的
a += b a = a + b
a -= b a = a - b
a *= b a = a * b
a /= b a = a / b
a //= b a = a // b
a%=b a = a % b
a**=b a = a ** b
a &= b a = a & b
a ^= b a = a ^ b
a >>= b a = a >> b
a <<= b a = a << b

数学运算符

数学运算符主要用于Python 中的数字

手术 操作员 例子 结果
指数 ** 2**3 8
5%3 2
楼层划分 // 4 // 3 1
分配 / 2 / 2 1
乘法 * 2 * 2 4
减法 - 1 - 2 -1
添加 + 1 + 2 3

所有这些运算只能用于Number类型的值。但有些运算可以用于Numbers以外的其他类型。

print("Hello " + "World") # This prints Hello World
# string concatenation

print("Hello" * 3) # This prints HelloHelloHello
# string repetition

print([1,2,3] + [4,5]) # This prints [1,2,3,4,5] 
# + combines both list

print([1] * 3) # This prints [1,1,1]
# * list repetition.

Enter fullscreen mode Exit fullscreen mode

布尔运算符

布尔运算符主要用于if条件或流控制,我们稍后会讨论。

与运算符 结果
假与假 错误的
真与假 错误的
真假 错误的
真与真 真的
或运算符 结果
假还是假 错误的
真或假 真的
对还是错 真的
真或真 真的
非运算符 结果
不正确 错误的
不假 真的

比较运算符

比较运算符用于比较两个值,并将其计算为一个布尔值。

手术 操作员 例子 结果
大于 > 5 > 2 真的
少于 < 5 < 2 错误的
大于或等于 >= 4 >= 3 真的
小于或等于 <= 4 <= 3 错误的
不等于 != 2 != 2 错误的
平等的 == 2 == 2 真的

if、elif 和 else 语句
有时我们希望代码基于一个或多个特定条件运行。这时,if、elif 和 else 语句就派上用场了。这三种语句的语法如下所示。

is_done = True

if is_done:
   print("The job is done") # This will be printed because the variable "is_done" is True
else:
   print("The job is not done") # This will not print 

Enter fullscreen mode Exit fullscreen mode

仅当if 语句的条件不为时, else 语句才会运行。如果我们想要多个条件,可以使用elif 语句。如果前一个if 语句或之前的elif 语句的计算结果为 ,则将检查elif 语句TrueFalse

my_grade = "B"

if my_grade == "A":
    print("Amazing")
elif my_grade == "B":
    print("Very Good")  # This will be printed
elif my_grade == "C":
    print("Good")
elif my_grade == "D":
    print("Bad")
elif my_grade == "E":
    print("Very Bad")
else:
    print("Failed")

Enter fullscreen mode Exit fullscreen mode

在上面的例子中,它打印<>Very Good,因为变量my_grade的值为,"B"并且它忽略其余的elif 语句else 语句

循环
Python 有两种主要机制用于一遍又一遍地或以特定的次数重复执行代码块。while
循环for循环。

while循环用于某个条件为True时重复执行一段代码。while
循环的语法如下所示。


count = 0
while count < 5:
    print(count)
    count += 1

Enter fullscreen mode Exit fullscreen mode

在这个例子中,循环将持续到count变量的值为5为止。因为我们的条件是,当 count 小于 5 时重复执行代码块,所以在代码块中,我们将 count 的值加 1

另一方面,for循环会按特定次数执行代码块。for循环的语法如下所示。


avengers = ["Iron Man", "Captain America","Thor", "Hulk", "Black Widow", "Hawkeye"]

for avenger in avengers:
    print(avenger) 

Enter fullscreen mode Exit fullscreen mode

在此示例中,我们为avengers列表中的六个值分别分配了变量名avenger。通常,它从索引0开始,直到最后一个值。在每次迭代中,avenger变量都会保存列表中的不同项。

如果您想获取列表中的索引range而不是值。您可以使用和len函数。

range函数有三个参数range(start,stop,step) 。start默认值为0,step 的默认值为1。如果没有提供startstep ,则range函数中提供的任何值都将作为stop,并且应该是一个整数。

print(range(5)) # This prints range(0,5)
print(range(0,5,1)) # This is equivalent in the print statement above
print(range(0,5)) # This is equivalent in the print statement above

# We can convert the return value of the range function into a List. Using the list function

print(list(range(5))) # This prints [0,1,2,3,4] does not include the stop

Enter fullscreen mode Exit fullscreen mode

len函数返回容器中项目的数量。我们可以在列表字符串元组集合字典中使用它。

print(len("abc")) # This prints 3. The number of characters in the String
print(len([1,2,3,4,5])) # This prints 5. The number of values in the List
print(len((1,2,3,4))) # This prints 4. The number of values in the Tuple
print(len({1,2,3,3})) # This prints 3. The number of values in the Set
print(len({"a":"eyy","b":"bee","c":"si"})) # This prints 3. The number of keys in the Dictionary
Enter fullscreen mode Exit fullscreen mode

因此range和函数是获取列表索引len的良好组合

for index in range(len(avengers)):
    print(f"{index} - {avengers[index]}") # This prints the index and the corresponding value at that index in each iteration
Enter fullscreen mode Exit fullscreen mode

有些语句仅在循环内有效。它们是breakcontinue语句。

break语句用于立即停止或退出循环。

i = 0
while True:
    count += 1
    if count == 3:  # When the value of count is 3. This loop will exit
        break
    else:
        print(count)

for avenger in avengers:
    if avenger == "Thor":  # When the value of avenger is Thor. This loop will exit
        break
    else:
        print(avenger)
Enter fullscreen mode Exit fullscreen mode

continue语句将跳过当前迭代并继续执行下一次迭代。它会返回到循环声明处,然后再继续执行代码块。

i = 0
while True:
    count += 1
    if count == 3:  # Will not print 3
        continue
    else:
        print(count)

for avenger in avengers:
    if avenger == "Thor":  # Will not print Thor
        continue
    else:
        print(avenger)
Enter fullscreen mode Exit fullscreen mode

布尔值

布尔类型只有两个值TrueFalse。当我们在值之间使用比较运算符布尔运算符时,它们的计算结果为单个布尔值。布尔值用于if条件、while循环等

is_absent = False
my_fav_num = 5

print(is_absent) # This prints False
print(my_fav_num > 1) # This True because it compares if 5 is greater than 1 which evaluates to True
print(True and False) # This prints False
print(True or False) # This prints True
print(not False) # This prints True

if is_absent:
    print("Mark is present")  # This will not be printed because is_absent is False
else:
    print("Mark is absent")  # This will be printed

while True:  # This is an example of an infinite loop
    print("This will not stop")  # Press Ctrl+C to Stop

Enter fullscreen mode Exit fullscreen mode

TrueFalse分别是10。它们的类型不同,但值相同,只是打印逻辑不同。

print(True == 1) # This prints True
print(False == 0) # This prints True

Enter fullscreen mode Exit fullscreen mode

字符串

字符串显然是文本的值。在 Python 中使用字符串相对简单有趣。我们可以用双引号"或单引号创建字符串'。如果字符串以单引号开头,
则也必须以单引号结尾。如果字符串以双引号开头,则也必须以双引号结尾。

my_name = "Mark"

my_favorite_language = 'Python'

my_favorite_book = 'The Sum of all Fears"
# This will raise a SyntaxError because it starts with a single-quote but ends with a double-quote
Enter fullscreen mode Exit fullscreen mode

我们可以使用索引访问字符串中的特定值索引是该字符(一个字符是一个像“a”这样的字符串)在字符串中的位置。索引是一个整数,从 0、1、2、3 开始,直到字符串中的最后一个字符,该字符的索引等于字符串的长度减 1。索引时也可以使用负数,-1 表示字符串中的最后一个字符的索引,-2 表示倒数第二个字符的索引,依此类推。

字符串——‘Mark’ 一个 r
正向索引 0 1 2 3
负索引 -4 -3 -2 -1

first_letter = my_name[0] # returns the first character in my_name variable which is "M"

print(first_letter) # This will print "M"

first_letter = my_name[-4] # returns the first character in my_name variable which is also "M" using negative-indexing

print(first_letter) # This will print "M"
Enter fullscreen mode Exit fullscreen mode

我们可以使用Python 字符串中一个很棒的功能——切片。切片是指从给定数据类型中提取特定部分的数据。我们可以指定提取的起始位置、结束位置以及所需的步数。my_name[0:4:1]在本例中,my_name 是一个字符串变量,其值为“Mark”。切片操作以方括号开始,0表示起始点,4表示结束点(不包括起始点),最后一个1表示步长,即从起始结束的步长

guess_my_value = my_name[0:4:1]
# It will extract the portion of the characters from index 0 to index 4 but not including, with a step of 1
# so it extract 'M', 'a', 'r', 'k' with an index of 0,1,2,3 respectively. The step has a default value of 1.

print(guess_my_value) # This will print "Mark"

print(my_name[0:4]) # This will still print "Mark"

print(my_name[:]) # This will still print "Mark"

print(my_name[0:]) # This will still print "Mark"

Enter fullscreen mode Exit fullscreen mode

注意:字符串是不可变的,这意味着我们不能更改或删除该字符串中的特定字符,除非
您为保存该字符串的变量分配新值。


my_name[0] = "A" # This will raise a TypeError 'str' object does not support item assignment
my_name = "Polo" # This assigns a new value for my_name
print(my_name) # This will print "Polo"


Enter fullscreen mode Exit fullscreen mode

字符串有很多方法可以帮助我们解决一些基本问题。大多数方法都会返回一个新的字符串,并且不会改变原始字符串。

my_name = "Mark"

print(my_name.upper()) # This prints "MARK"
# The "upper" method returns a new string version as all in uppercase

print(my_name.lower()) # This prints "mark"
# The "lower" method returns a new string version as all in lowercase

print(my_name.islower()) # This prints False
# The "islower" method returns a Boolean indicating if the String contains all lowercase letters
# it returns True if all letters are lowercase else return False

print(my_name.isupper()) # This prints False
# The "isupper" method returns a Boolean indicating if the String contains all uppercase letters
# it returns True if all letters are lowercase else return False

print(my_name.isalpha()) # This prints True
# The "isalpha" method returns a Boolean indicating if all characters in the String 
#  are alphabetic  it returns True else it returns False

print(my_name.isdigit()) # This prints False
# The "isdigit" method returns a Boolean indicating if all characters in the String
# are numbers it returns True else it returns False

print(my_name.index("ark")) # This prints 1
# The "index" method searches a substring in String and returns the starting Index
# of the substring else this method raises a ValueError.

print("a,b,c,d".split(",")) # This prints ["a","b","c","d"]
# The "split" method obviously splits the String with parameter separator and returns a
# list of all strings. It also has a second parameter which is a number that indicates 
# the number of splits we want.

print(my_name.startswith("Ma")) # This prints True
# The "startswith" method returns a Boolean indicating if the String
# starts with a certain substring else it returns False     

print(my_name.startswith("rc")) # This prints False
# The "endswith" method returns a Boolean indicating if the String
# ends with a ceratin substring else it returns False   
Enter fullscreen mode Exit fullscreen mode

还有很多方法我在这个例子中没有讨论到,大家可以自己尝试一下。

数字

Python 中的数字数据类型有很多种。例如整数浮点数八进制十六进制二进制复数集合(稍后会讨论)布尔值十进制分数数字并非像字符串列表那样单一类型,而是多种相互关联的类型。

import fractions
import decimal

my_num = 5 # Integer
pi = 3.14 # Floating-point number
ten = 0o012 # Octal
x = 0x123 # Hex
two = 0b010 # Binary
unique_nums = {1,2,3,2,3} # Sets
is_done = True # Boolean
one_and_a_half = fractions.Fraction(1/2)  # Fraction
one_over_three = decimal.Decimal(1/3) # Decimal
Enter fullscreen mode Exit fullscreen mode

好的,我不会谈论太多这些类型,因为我们主要使用整数浮点数

如果要将字符串整数浮点数一起使用,则必须先使用该str函数转换该数字,然后再使用它。

print(str(2) + "is two")
print(str(3.0) + "is three")
print(4.1+ "is four point one") This raises a TypeError: unsupported operand type(s) for +: 'float' and 'str'
Enter fullscreen mode Exit fullscreen mode

你一定想知道为什么布尔类型和数字类型相关。正如我之前所说,
布尔值True和数字分别False只是10,它们只是不同的打印逻辑。

print(True == 1) # This prints True
print(False == 0) # This prints True
print(isinstance(True,int)) # This prints True
Enter fullscreen mode Exit fullscreen mode

集合则使用某些运算符和方法进行一些数学运算。我们稍后再讨论集合

列表

列表是充当其他值容器的值。它可以保存相同类型的多个值,也可以保存任何类型的多个值。在其他编程语言中,它被称为数组。我们可以使用方括号声明一个列表[]。我们可以将值放入列表中,并使用逗号, 分隔它们[1,2,3,4,5]

numbers = [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

我们可以使用索引访问列表中的特定值索引是该值在列表中的位置。索引是一个整数,从 0、1、2、3 开始,直到列表的最后一个项,其索引等于列表的长度减 1。索引时也可以使用负数,-1 表示列表中的最后一个索引,-2 表示倒数第二个索引,依此类推。与字符串一样,列表也有正索引索引。

one = numbers[0] # numbers[0] holds the value of 1in the List
two = numbers[1] # numbers[1] holds the value of 2 in the List
five = numbers[-1] # numbers[-1] holds the value of 5 in the List

# We can get the length of the array using the "len" method. We only pass the name of the variable that holds the List.

len_of_numbers = len(numbers) # len(numbers) returns 5

# If we access an index that is more than the number of values in the List
# you will get an IndexError

guess_this_number = numbers[1000] # This will raise the IndexError

Enter fullscreen mode Exit fullscreen mode

如果要检查列表中的每个项目。您可以使用for 循环

avengers = ["Iron Man","Captain America","Thor","Hulk","Black Widow","Hawkeye"]

for avenger in avengers: 
      print(avenger) # prints every avenger each in a new line

# If you want to use the index instead of the value
# we can also use that using for loops with the help of "range" and "len" functions

for index in range(len(avengers)):
      print(index) # prints the index each in a new line

# Tip: Instead of checking the length of a List in a condition
# just use the list instead

data = ["one"] 

if len(data):
    print("This will be printed.")

# Use this instead

if data:
    print("This will be printed.")

Enter fullscreen mode Exit fullscreen mode

就像字符串一样,我们可以在列表中使用切片

l = [1,2,3,4,5]

# list[start:stop:step] 

len_l = len(l) # has a value of 5
half = len_l//2

first_half = l[0:half] # l[0:half] will evaluate to l[0:2] is also equivalent to l[:2]

print(first_half) # This will print [1,2]

second_half = l[half:len_l] # l[half:l] will evaluate to l[2:5] is also equivalent l[2:] 

print(second_half) # This will print [3,4,5]

odd_nums = l[0:len_l:2] 
#  l[0:len_l:2] will evalute to l[0:5:2] the 0 our start, the 5 is our stop and the step is 2 
#  l[0:5:2] is also equivalent to l[0::2] or l[::2]

print(odd_nums) # This will print [1,3,5]

reverse_l = l[::-1] 
#  l[::-1] This reverse the start and stop meaning we will start at the last item and stop 
# with the first item. [::-1] is also equivalent to l[len(l)::-1]

print(reverse_l) # This will print [5,4,3,2,1]

Enter fullscreen mode Exit fullscreen mode

列表有许多方法可以让我们的生活更轻松。


avengers.append("Ant-Man") 
# The "append" method add a new item at
#  the end of List

avengers.count("Iron Man") # returns 1
# The "count" method counts how many times
#  the value passed appears

avengers.extend(["Doctor Strange","Spiderman","Black Panther"])
# The "extend" method adds all items 
# passed at the end of the List. The parameter passed must be an Iterable object.

avengers.index("Captain America") # returns 1
# The "index" method returns the first index of the value passed.
# If the value does not exist this method raises a ValueError.

avengers.insert(0,"Captain Marvel")
# The "insert" method obviously inserts a value 
# at a specified index but does not replace the
#  current value at that position.

avengers.append("Thanos")
avengers.remove("Thanos") # returns 1
# The "remove" method obviously removes the first occurence of the value passed.
# If the value does not exist this method raises a ValueError.

avengers.reverse()
# The "reverse" method reverses the position of each item in the List.
# If the List looks like this my_list = [1,2,3]
# then we use l.reverse()
# then my_list would look like this [3,2,1]

avengers.pop()
# The "pop" method removes the last item in the List and returns it.
# We can specify the index to remove in pop method as a parameter
# If the index is not valid or if the List is empty this method raises an 
# IndexError.

Enter fullscreen mode Exit fullscreen mode

元组

元组 (Tuple)类似于列表 (List),但它们之间的区别在于列表可变的,这意味着我们可以更改或删除列表
内的值,而元组(Tuple)是不可变的,这意味着 我们不能更改或删除元组 (Tuple)上的任何值。我们可以使用括号来创建元组 (Tuple)

my_favorite_numbers = (1,21,19)

# If you only assign one value in the Tuple without using a comma 
# Python will treat that as an expression and in turn that variable
# will not be a tuple instead will the first item in the parentheses

my_secret_nums = (666) 

print(my_secret_nums) # will print 666 instead of (666)

my_new_secret_nums = (666,)

print(my_new_secret_nums) # prints (666,)
Enter fullscreen mode Exit fullscreen mode

元组几乎类似于列表,我们可以使用切片连接,可以使用索引访问值,还可以使用*运算符重复元组。但是我们不能在元组中添加或更改任何值。元组只有两个方法:索引计数

secret_hero_real_names = ("Bruce Wayne","Steve Rogers","Clark Kent","Peter Parker")

secret_hero_real_names.count("Bruuce Wayne") #returns 0
secret_hero_real_names.count("Peter Parker") #returns 1 
secret_hero_real_names.index("Steve Rogers") # returns 1
Enter fullscreen mode Exit fullscreen mode

字典

字典也是像列表一样的数据容器,但与列表不同的是,在字典中,我们通过索引访问列表中的特定值;而在字典中,我们使用属性来访问值,而键或属性又包含一个值。字典中的项是无序的,而列表中的项是有序的。我们可以使用花括号创建一个__Dictionary{}


books_currently_reading_bookmark = {
   "Angel & Demons" :  484,
   "Da Vinci Code": 100
}

# We can use a key with a type of "string","integer" or "tuples" in Dictionaries

d = { 1 : "one" }
print(d[1]) # prints "one"

d1 = { (1,2,3,4,5,6,7,8,9,10): "one-ten"}

print(d[(1,2,3,4,5,6,7,8,9,10)]) # prints "one-ten"

#We cannot use a type of "dictionary" or "list" as a key in Dictionaries

d2 = { [1,2,3] : "one-three" } # This will raise a TypeError : unhashable type: 'list'
Enter fullscreen mode Exit fullscreen mode

我们可以随时在字典中添加新的键值对。

letters_sounds = {}

letters_sounds["a"] = "eyyy"
letters_sounds["b"] = "bee"

print(letters_sound) # prints {'a': 'eyyy', 'b': 'bee'}
Enter fullscreen mode Exit fullscreen mode

如果我们检查字典中不存在的键,就会出现错误。

print(letters_sounds["c"]) # This will raise a KeyError which means that key "c" does not exist in the letters_sounds Dictionary.
Enter fullscreen mode Exit fullscreen mode

我们可以使用字典in中的运算符或get方法 来检查字典中是否存在某个键。

if "c" in letters_sounds: # Check if "c" exists
    print(letters_sounds["c"])
else:
   print("letters_sounds does not have a 'c' key")


print(letters_sounds.get("c") == None) # prints True
# The get method has a second parameter which is the default value 
# that will be used if the key does not exist in the Dictionary

print(letters_sounds.get("c",0)) # prints 0
Enter fullscreen mode Exit fullscreen mode

字典有许多有用的方法,可以帮助解决处理字典时的一些问题。

new_letters_sounds = {
      "a": "ayy",
      "c" : "si"
}

letters_sounds.update(new_letters_sounds) 
# The "update" method adds or updates new keys in the dictionary it accepts 
# an Iterable type as a parameter or the source

letters_sounds.setdefault("c","sii") 
# The "setdefault" method add a new key and a default value in the dictionary
# if the key doesn't exist in the dictionary, if it exists it returns the value of that key

for key in letters_sounds.keys():
    print(key) # This prints "a", "b" and "c" respectively each in a new line
# The "keys" method returns all keys in the dictionary. This does not return a list.
# Instead it returns a set-like object.

for val in letters_sounds.values(): 
    print(val) # This prints "ayy", "bee" and "si" each in a newline
# The "keys" method returns all keys in the dictionary. This does not return a list.
# Instead it returns a set like object.

# If you want to access the key and the value in a loop.
# You can use the "items" method.
for key, value in tuple(letters_sounds.items()):
    print(f"{key}:{value}") # This prints "a:ayy", "b:bee" and "c:si" respectively each in a newline
# The "items" method returns the key and value in a set like object.

letters_sounds.pop("c")
# The "pop" method removes a key and its value in the Dictionary.
# If the key does not exist this raises a KeyError.

letters_sounds.clear()
# The "clear" method removes all the keys and values in the Dictionary.
Enter fullscreen mode Exit fullscreen mode

集合 (Set)和列表 (List)字典 (Dictionaries)元组 (Tuple)一样,也是容器。区别在于,集合是有序集合,像元组一样不可变集合本身可变,但其值必须不可变),并且只保存唯一值。集合使用花括号函数声明,并且集合看起来像字典,区别在于集合没有键 (key) {}set

nums = {1,2,3,4,3,4}
nums_2 = set([1,2,3,4,4,5,5]) 
print(nums)  # This prints {1,2,3,4} because Sets only holds unique values.

print(nums_2) # This prints {1,2,3,4,5}
Enter fullscreen mode Exit fullscreen mode

由于Set是按序排列的,我们无法访问特定的值。它不像ListTuple那样具有索引功能。


print(nums[0])
# This raises a TypeError: 'set' object does not support indexing.
Enter fullscreen mode Exit fullscreen mode

尽管集合被称为不可变的,
但它具有可以 从集合中更改或删除特定值的方法。

nums.add(4) 
# The "add" method adds a new value in Set if it does not 
# already exist. If already exists this method does nothing.

nums.remove(1)
# The "remove" method removes a specific value from the Set.
# If the value does not exist it raises a KeyError.

nums.clear()
# The "clear" method obviously removes all the values present
# in the Set.
Enter fullscreen mode Exit fullscreen mode

我们可以在集合中使用其他类型中不可用的某些操作。

s1 = {1,2,3}
s2 = {3,4,5,6}

print(s1 | s2)  # This prints {1,2,3,4,5,6} 
# This operation is called "union" it combines both sets and returns a new set.
# It also have a equivalent method on sets called "union" suprise, suprise.
print(s1.union(s2))  # Also prints {1,2,3,4,5,6} 

print(s1 & s2) # This prints {3}
# This operation is called "intersection" it finds the common elements in both sets and returns it in a set.
# It also have a equivalent method on sets called "intersection" suprise, suprise.
print(s1.intersection(s2))  # Also prints {3}

print(s1 - s2)  # This prints {1, 2}
# This operation is called "difference" it finds the difference between the first Set and the second Set and returns a new Set.
# So in this example it calculates what elements "s1" has that "s2" does not have.
# It also have a equivalent method on sets called "difference" suprise, suprise.
print(s1.difference(s2)) # Also prints {1,2}

print(s1 ^ s2) # This prints {1,2,4,5,6}
# This operation is called "symmetric_difference" it finds the elements that are not common between the two sets and returns it as a Set.
# So in this example it calculates what unique elements between "s1" and "s2" has and returns it.
# It also have a equivalent method on sets called "symmetric_difference" suprise, suprise.
print(s1.symmetric_difference(s2)) # Also prints {1,2,4,5,6}
Enter fullscreen mode Exit fullscreen mode

请关注我关于回顾 Python 的这篇文章的下一部分,它将涉及处理异常函数列表元组字典集合理解模块

感谢大家阅读这篇文章。

祝你有美好的一天😃!

鏂囩珷鏉ユ簮锛�https://dev.to/macmacky/reviewing-python-fundamentals-29ge
PREV
变异没问题
NEXT
如何从头开始配置 Webpack 和 Vue