在目前的编程语言中,Python的抽象程度是最高的,是最接近自然语言的,很容易上手。你可以用它来完成很多任务,比如数据科学、机器学习、Web开发、脚本编写、自动化等。
▍1、for循环中的else条件
这是一个for-else方法,循环遍历列表时使用else语句 下面举个例子,比如我们想检查一个列表中是否包含奇数 那么可以通过for循环,遍历查找
numbers = \[ 2 , 4 , 6 , 8 , 1 \]
for number in numbers:
if number % 2 == 1 :
print ( number)
break
else :
print ( "No odd numbers" )
如果找到了奇数,就会打印该数值,并且执行break语句,跳过else语句。 没有的话,就不会执行break语句,而是执行else语句。
▍2、从列表中获取元素,定义多个变量
my\_list = \[ 1 , 2 , 3 , 4 , 5 \]
one, two, three, four, five = my\_list
▍3、使用heapq模块,获取列表中n个最大或最小的元素
import heapq
scores = \[ 51 , 33 , 64 , 87 , 91 , 75 , 15 , 49 , 33 , 82 \]
print ( heapq. nlargest( 3 , scores) )
print ( heapq. nsmallest( 5 , scores) )
▍4、将列表中的所有元素作为参数传递给函数
my\_list = \[ 1 , 2 , 3 , 4 \]
print ( my\_list)
print ( \* my\_list)
def sum \_of\_elements( \* arg) :
total = 0
for i in arg:
total += i
return total
result = sum \_of\_elements( \* \[ 1 , 2 , 3 , 4 \] )
print ( result)
▍5、获取列表的所有中间元素
\_, \* elements\_in\_the\_middle, \_ = \[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 \]
print ( elements\_in\_the\_middle)
▍6、使用一行代码赋值多个变量
one, two, three, four = 1 , 2 , 3 , 4
▍7、列表推导式
只用一行代码,便可完成对数组的迭代以及运算。 比如,将列表中的每个数字提高一倍。
numbers = \[ 1 , 2 , 3 , 4 , 5 \]
squared\_numbers = \[ num \* num for num in numbers\]
print ( squared\_numbers)
推导式不仅列表能用,字典、集合、生成器也能使用。 下面看一下,使用字典推导式,将字典的值提高一倍。
dictionary = { 'a' : 4 , 'b' : 5 }
squared\_dictionary = { key: num \* num for ( key, num) in dictionary. items( ) }
print ( squared\_dictionary)
▍8、通过Enum枚举同一标签或一系列常量的集合
枚举是绑定到唯一的常量值的一组符号名称(成员)。 在枚举中,成员可以通过身份进行比较,枚举本身可以迭代。
from enum import Enum
class Status ( Enum) :
NO\_STATUS = \- 1
NOT\_STARTED = 0
IN\_PROGRESS = 1
COMPLETED = 2
print ( Status. IN\_PROGRESS. name)
print ( Status. COMPLETED. value)
▍9、重复字符串
name = "Banana"
print ( name \* 4 )
▍10、比较3个数字的大小
如果想比较一个值和其他两个值的大小情况,你可以使用简单的数学表达式。
1 < x < 10
这个是最简单的代数表达式,在Python中也是可以使用的。
x = 3
print ( 1 < x < 10 )
print ( 1 < x and x < 10 )
▍11、使用1行代码合并字典
first\_dictionary = { 'name' : 'Fan' , 'location' : 'Guangzhou' }
second\_dictionary = { 'name' : 'Fan' , 'surname' : 'Xiao' , 'location' : 'Guangdong, Guangzhou' }
result = first\_dictionary | second\_dictionary
print ( result)
▍12、查找元组中元素的索引
books = ( 'Atomic habits' , 'Ego is the enemy' , 'Outliers' , 'Mastery' )
print ( books. index( 'Mastery' ) )
▍13、将字符串转换为字符串列表
假设你在函数中获得输出,原本应该是一个列表,但实际上却是一个字符串。
input = "\[1,2,3\]"
你可能第一时间会想到使用索引或者正则表达式。 实际上,使用ast模块的literal_eval方法就能搞定。
import ast
def string\_to\_list( string) :
return ast. literal\_eval( string)
string = "\[1, 2, 3\]"
my\_list = string\_to\_list( string)
print ( my\_list)
string = "\[\[1, 2, 3\],\[4, 5, 6\]\]"
my\_list = string\_to\_list( string)
print ( my\_list)
▍14、计算两数差值
def subtract ( a, b) :
return a - b
print ( ( subtract( 1 , 3 ) ) )
print ( ( subtract( 3 , 1 ) ) )
def subtract ( a, b) :
return a - b
print ( ( subtract( a= 1 , b= 3 ) ) )
print ( ( subtract( b= 3 , a= 1 ) ) )
▍15、用一个print()语句打印多个元素
print ( 1 , 2 , 3 , "a" , "z" , "this is here" , "here is something else" )
▍16、在同一行打印多个元素
print ( "Hello" , end= "" )
print ( "World" )
print ( "Hello" , end= " " )
print ( "World" )
print ( 'words' , 'with' , 'commas' , 'in' , 'between' , sep= ', ' )
▍17、打印多个值,在每个值之间使用自定义分隔符
print ( "29" , "01" , "2022" , sep= "/" )
print ( "name" , "domain.com" , sep= "@" )
▍18、不能在变量名的开头使用数字
four\_letters = "abcd"
4 \_letters = "abcd"
▍19、不能在变量名的开头使用运算符
+ variable = "abcd"
▍20、数字的第一位不能是0
number = 0110
▍21、在变量名的任何地方使用下划线
a\_\_\_\_\_\_b = "abcd"
\_a\_b\_c\_d = "abcd"
这并不意味着,你可以无限使用,为了代码的易读性,还是需要合理使用。
▍22、使用下划线分割数值较大的数字
print ( 1 \_000\_000\_000)
print ( 1 \_234\_567)
▍23、反转列表
my\_list = \[ 'a' , 'b' , 'c' , 'd' \]
my\_list. reverse( )
print ( my\_list)
▍24、使用步进函数对字符串切片
my\_string = "This is just a sentence"
print ( my\_string\[ 0 : 5 \] )
print ( my\_string\[ 0 : 10 : 3 \] )
▍25、反向切片
my\_string = "This is just a sentence"
print ( my\_string\[ 10 : 0 : \- 1 \] )
print ( my\_string\[ 10 : 0 : \- 2 \] )
▍26、使用开始或结束索引进行切片
my\_string = "This is just a sentence"
print ( my\_string\[ 4 : \] )
print ( my\_string\[ : 3 \] )
▍27、/和//的区别
print ( 3 / 2 )
print ( 3 // 2 )
▍28、==和is的区别
is :检查两个变量是否指向同一对象内存中
\== :比较两个对象的值
first\_list = \[ 1 , 2 , 3 \]
second\_list = \[ 1 , 2 , 3 \]
print ( first\_list == second\_list)
print ( first\_list is second\_list)
third\_list = first\_list
print ( third\_list is first\_list)
▍29、合并字典
dictionary\_one = { "a" : 1 , "b" : 2 }
dictionary\_two = { "c" : 3 , "d" : 4 }
merged = { \* \* dictionary\_one, \* \* dictionary\_two}
print ( merged)
▍30、检查字符串是否大于另一字符串
first = "abc"
second = "def"
print ( first < second)
second = "ab"
print ( first < second)
▍31、检查字符串是否以特定字符开头(不使用索引)
my\_string = "abcdef"
print ( my\_string. startswith( "b" ) )
▍32、使用id()查找变量的唯一id
print ( id ( 1 ) )
print ( id ( 2 ) )
print ( id ( "string" ) )
▍33、整数、浮点数、字符串、布尔值和元组都是不可变的
当变量被赋值为整数、浮点数、字符串、布尔值、元组这些不可变类型后,该变量就会指向一个内存对象。 如果重新给变量再赋值,它的内存对象就会发生改变。
number = 1
print ( id ( number) )
print ( id ( 1 ) )
number = 3
print ( id ( number) )
print ( id ( 1 ) )
▍34、字符串和元组也是不可变的
name = "Fatos"
print ( id ( name) )
name = "fatos"
print ( id ( name) )
▍35、列表、集合和字典都是可变的
cities = \[ "Beijing" , "Guangzhou" , "chengdu" \]
print ( id ( cities) )
cities. append( "Beijing" )
print ( id ( cities) )
my\_set = { 1 , 2 , 3 , 4 }
print ( id ( my\_set) )
my\_set. add( 5 )
print ( id ( my\_set) )
▍36、把一个列表变成不可变的列表
my\_set = frozenset ( \[ 'a' , 'b' , 'c' , 'd' \] )
my\_set. add( "a" )
▍37、if-elif块可以在没有else块的情况下存在
def check\_number( number) :
if number > 0 :
return "Positive"
elif number == 0 :
return "Zero"
return "Negative"
print ( check\_number( 1 ) )
▍38、使用sorted()检查2个字符串是否为相同
def check\_if\_anagram( first\_word, second\_word) :
first\_word = first\_word. lower( )
second\_word = second\_word. lower( )
return sorted ( first\_word) == sorted ( second\_word)
print ( check\_if\_anagram( "testinG" , "Testing" ) )
print ( check\_if\_anagram( "Here" , "Rehe" ) )
print ( check\_if\_anagram( "Know" , "Now" ) )
▍39、获取字符的Unicode值
print ( ord ( "A" ) )
print ( ord ( "B" ) )
print ( ord ( "C" ) )
print ( ord ( "a" ) )
▍40、获取字典的键
dictionary = { "a" : 1 , "b" : 2 , "c" : 3 }
keys = dictionary. keys( )
print ( list ( keys) )
▍41、获取字典的值
dictionary = { "a" : 1 , "b" : 2 , "c" : 3 }
values = dictionary. values( )
print ( list ( values) )
▍42、交换字典的键、值位置
dictionary = { "a" : 1 , "b" : 2 , "c" : 3 }
reversed \_dictionary = { j: i for i, j in dictionary. items( ) }
print ( reversed )
▍43、将布尔值转换为数字
print ( int ( False ) )
print ( float ( True ) )
▍44、在算术运算中使用布尔值
x = 10
y = 12
result = ( x - False ) / ( y \* True )
print ( result)
▍45、将任何数据类型转换为布尔值
print ( bool ( .0 ) )
print ( bool ( 3 ) )
print ( bool ( "-" ) )
print ( bool ( "string" ) )
print ( bool ( " " ) )
▍46、将值转换为复数
print ( complex ( 10 , 2 ) )
print ( hex ( 11 ) )
▍47、在列表的第一个位置添加一个值
如果使用append(),将从列表的最后一个位置插入新值。 可以通过使用insert(),来指定插入新元素的索引和数值。 那么列表的第一个位置为0,即下标为0。
my\_list = \[ 3 , 4 , 5 \]
my\_list. append( 6 )
my\_list. insert( 0 , 2 )
print ( my\_list)
▍48、Lambda函数只能在一行代码中
comparison = lambda x: if x > 3 :
print ( "x > 3" )
else :
print ( "x is not greater than 3" )
报错。
▍49、Lambda中的条件语句应始终包含else语句
comparison = lambda x: "x > 3" if x > 3
运行上面的代码,报错。 这是由于条件表达式的特性,而不是lambda的导致的。
▍50、使用filter(),获得一个新对象
my\_list = \[ 1 , 2 , 3 , 4 \]
odd = filter ( lambda x: x % 2 == 1 , my\_list)
print ( list ( odd) )
print ( my\_list)
▍51、map()返回一个新对象
map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。
my\_list = \[ 1 , 2 , 3 , 4 \]
squared = map ( lambda x: x \* \* 2 , my\_list)
print ( list ( squared) )
print ( my\_list)
▍52、range()的step参数
for number in range ( 1 , 10 , 3 ) :
print ( number, end= " " )
▍53、range()默认从0开始
def range \_with\_zero( number) :
for i in range ( 0 , number) :
print ( i, end= ' ' )
def range \_with\_no\_zero( number) :
for i in range ( number) :
print ( i, end= ' ' )
range \_with\_zero( 3 )
range \_with\_no\_zero( 3 )
▍54、不需要和0比较长度
def get\_element\_with\_comparison( my\_list) :
if len ( my\_list) > 0 :
return my\_list\[ 0 \]
def get\_first\_element( my\_list) :
if len ( my\_list) :
return my\_list\[ 0 \]
elements = \[ 1 , 2 , 3 , 4 \]
first\_result = get\_element\_with\_comparison( elements)
second\_result = get\_element\_with\_comparison( elements)
print ( first\_result == second\_result)
▍55、可以在同一个作用域内多次定义一个方法
def get\_address( ) :
return "First address"
def get\_address( ) :
return "Second address"
def get\_address( ) :
return "Third address"
print ( get\_address( ) )
▍56、在外部直接访问私有属性
在定义属性或方法时,在属性名或者方法名前增加两个下划线,定义的就是私有属性或方法。 如果想要在外部访问,那么只需要在名称前面加上 ‘_类名’ 变成 ‘_类名__名称’。
class Engineer :
def \_\_init\_\_( self, name) :
self. name = name
self. \_\_starting\_salary = 62000
dain = Engineer( 'Dain' )
print ( dain. \_Engineer\_\_starting\_salary)
▍57、检查对象的内存使用情况
import sys
print ( sys. getsizeof( "bitcoin" ) )
▍58、定义一个方法,可以调用任意个参数
def get\_sum( \* arguments) :
result = 0
for i in arguments:
result += i
return result
print ( get\_sum( 1 , 2 , 3 ) )
print ( get\_sum( 1 , 2 , 3 , 4 , 5 ) )
print ( get\_sum( 1 , 2 , 3 , 4 , 5 , 6 , 7 ) )
▍59、使用super()或父类的名称调用父类的初始化
class Parent :
def \_\_init\_\_( self, city, address) :
self. city = city
self. address = address
class Child ( Parent) :
def \_\_init\_\_( self, city, address, university) :
super ( ) . \_\_init\_\_( city, address)
self. university = university
child = Child( 'Peking University' , 'Fudan University' , 'Tsinghua University' )
print ( child. university)
class Parent :
def \_\_init\_\_( self, city, address) :
self. city = city
self. address = address
class Child ( Parent) :
def \_\_init\_\_( self, city, address, university) :
Parent. \_\_init\_\_( self, city, address)
self. university = university
child = Child( 'Peking University' , 'Fudan University' , 'Tsinghua University' )
print ( child. university)
▍60、在类中使用 + 操作符
在两个int数据类型之间使用 + 运算符时,将得到它们的和。 而在两个字符串数据类型之间使用它时,会将其合并。
print ( 10 + 1 ) \# 两数相加
print ( 'first' + 'second' )
这个就是操作符重载,你还可以在类中使用(__add__)。
class Expenses :
def \_\_init\_\_( self, rent, groceries) :
self. rent = rent
self. groceries = groceries
def \_\_add\_\_( self, other) :
return Expenses( self. rent + other. rent,
self. groceries + other. groceries)
april\_expenses = Expenses( 1000 , 200 )
may\_expenses = Expenses( 1000 , 300 )
total\_expenses = april\_expenses + may\_expenses
print ( total\_expenses. rent)
print ( total\_expenses. groceries)
▍61、在类中使用 < 和 == 操作符
下面定义一个操作重载示例( < 操作符),使用__lt__方法。
class Game :
def \_\_init\_\_( self, score) :
self. score = score
def \_\_lt\_\_( self, other) :
return self. score < other. score
first = Game( 1 )
second = Game( 2 )
print ( first < second)
class Journey :
def \_\_init\_\_( self, location, destination, duration) :
self. location = location
self. destination = destination
self. duration = duration
def \_\_eq\_\_( self, other) :
return ( ( self. location == other. location) and
( self. destination == other. destination) and
( self. duration == other. duration) )
first = Journey( 'Location A' , 'Destination A' , '30min' )
second = Journey( 'Location B' , 'Destination B' , '30min' )
print ( first == second)
\_\_sub\_\_( ) for -
\_\_mul\_\_( ) for \*
\_\_truediv\_\_( ) for /
\_\_ne\_\_( ) for !=
\_\_ge\_\_( ) for >=
\_\_gt\_\_( ) for >
▍62、为类的对象定义自定义的可打印版本
class Rectangle :
def \_\_init\_\_( self, a, b) :
self. a = a
self. b = b
def \_\_repr\_\_( self) :
return repr ( 'Rectangle with area=' + str ( self. a \* self. b) )
print ( Rectangle( 3 , 4 ) )
▍63、交换字符串中字符的大小写
string = "This is just a sentence."
result = string. swapcase( )
print ( result)
▍64、检查字符串是否都是空格
string = " "
result = string. isspace( )
print ( result)
▍65、检查字符串是否都是字母或数字
name = "Password"
print ( name. isalnum( ) )
name = "Secure Password "
print ( name. isalnum( ) )
name = "S3cur3P4ssw0rd"
print ( name. isalnum( ) )
name = "133"
print ( name. isalnum( ) )
▍66、检查字符串是否都是字母
string = "Name"
print ( string. isalpha( ) )
string = "Firstname Lastname"
print ( string. isalpha( ) )
string = "P4ssw0rd"
print ( string. isalpha( ) )
▍67、根据参数删除字符
string = "This is a sentence with"
print ( string. rstrip( ) )
string = "this here is a sentence…..,,,,aaaaasd"
print ( string. rstrip( ".,dsa" ) )
string = "ffffffffFirst"
print ( string. lstrip( "f" ) )
▍68、检查字符串是否为数字
string = "seven"
print ( string. isdigit( ) )
string = "1337"
print ( string. isdigit( ) )
string = "5a"
print ( string. isdigit( ) )
string = "2\*\*5"
print ( string. isdigit( ) )
▍69、检查字符串是否为中文数字
string = "四二六七三"
print ( string. isdigit( ) )
print ( string. isnumeric( ) )
▍70、检查字符串是否所有单词都是大写开头
string = "This is a sentence"
print ( string. istitle( ) )
string = "10 Python Tips"
print ( string. istitle( ) )
string = "How to Print A String in Python"
print ( string. istitle( ) )
string = "PYTHON"
print ( string. istitle( ) )
▍71、在元组中使用负索引
numbers = ( 1 , 2 , 3 , 4 )
print ( numbers\[ \- 1 \] )
print ( numbers\[ \- 4 \] )
▍72、在元组中嵌套列表和元组
mixed\_tuple = ( ( "a" \* 10 , 3 , 4 ) , \[ 'first' , 'second' , 'third' \] )
print ( mixed\_tuple\[ 1 \] )
print ( mixed\_tuple\[ 0 \] )
▍73、快速统计元素在列表中出现的次数
names = \[ "Besim" , "Albert" , "Besim" , "Fisnik" , "Meriton" \]
print ( names. count( "Besim" ) )
▍74、使用slice()获取元素
my\_list = \[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 \]
slicing = slice ( \- 4 , None )
print ( my\_list\[ slicing\] )
print ( my\_list\[ \- 3 \] )
string = "Data Science"
slice \_object = slice ( 5 , None )
print ( string\[ slice \_object\] )
▍75、计算元素在元组中出现的次数
my\_tuple = ( 'a' , 1 , 'f' , 'a' , 5 , 'a' )
print ( my\_tuple. count( 'a' ) )
▍76、获取元组中元素的索引
my\_tuple = ( 'a' , 1 , 'f' , 'a' , 5 , 'a' )
print ( my\_tuple. index( 'f' ) )
▍77、步进获得元组
my\_tuple = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
print ( my\_tuple\[ : : 3 \] )
▍78、通过索引获取子元组
my\_tuple = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 )
print ( my\_tuple\[ 3 : \] )
▍79、将列表、集合、字典中所有元素删除
my\_list = \[ 1 , 2 , 3 , 4 \]
my\_list. clear( )
print ( my\_list)
my\_set = { 1 , 2 , 3 }
my\_set. clear( )
print ( my\_set)
my\_dict = { "a" : 1 , "b" : 2 }
my\_dict. clear( )
print ( my\_dict)
▍80、合并集合
first\_set = { 4 , 5 , 6 }
second\_set = { 1 , 2 , 3 }
print ( first\_set. union( second\_set) )
还可以使用update()方法,将第二个集合的元素插入到第一个集合中去。
first\_set = { 4 , 5 , 6 }
second\_set = { 1 , 2 , 3 }
first\_set. update( second\_set)
print ( first\_set)
▍81、在函数里输出结果
def is \_positive( number) :
print ( "Positive" if number > 0 else "Negative" )
is \_positive( \- 3 )
▍82、if语句中的多个条件
math\_points = 51
biology\_points = 78
physics\_points = 56
history\_points = 72
my\_conditions = \[ math\_points > 50 , biology\_points > 50 ,
physics\_points > 50 , history\_points > 50 \]
if all ( my\_conditions) :
print ( "Congratulations! You have passed all of the exams." )
else :
print ( "I am sorry, but it seems that you have to repeat at least one exam." )
▍83、在一个if语句中,至少满足多个条件中的一个
math\_points = 40
biology\_points = 78
physics\_points = 56
history\_points = 72
my\_conditions = \[ math\_points > 50 , biology\_points > 50 ,
physics\_points > 50 , history\_points > 50 \]
if any ( my\_conditions) :
print ( "Congratulations! You have passed all of the exams." )
else :
print ( "I am sorry, but it seems that you have to repeat at least one exam." )
▍84、任何非空字符串都为True
print ( bool ( "Non empty" ) )
print ( bool ( "" ) )
▍85、任何非空列表、元组、字典都为True
print ( bool ( \[ \] ) )
print ( bool ( set ( \[ \] ) ) )
print ( bool ( { } ) )
print ( bool ( { "a" : 1 } ) )
▍86、None、False、0都为False
print ( bool ( False ) )
print ( bool ( None ) )
print ( bool ( 0 ) )
▍87、在函数中使用全局变量
string = "string"
def do\_nothing( ) :
string = "inside a method"
do\_nothing( )
print ( string)
string = "string"
def do\_nothing( ) :
global string
string = "inside a method"
do\_nothing( )
print ( string)
▍88、计算字符串或列表中元素的数量
使用collections中的Counter计算字符串或列表中元素的数量。
from collections import Counter
result = Counter( "Banana" )
print ( result)
result = Counter( \[ 1 , 2 , 1 , 3 , 1 , 4 , 1 , 5 , 1 , 6 \] )
print ( result)
▍89、检查2个字符串是否为相同
from collections import Counter
def check\_if\_anagram( first\_string, second\_string) :
first\_string = first\_string. lower( )
second\_string = second\_string. lower( )
return Counter( first\_string) == Counter( second\_string)
print ( check\_if\_anagram( 'testinG' , 'Testing' ) )
print ( check\_if\_anagram( 'Here' , 'Rehe' ) )
print ( check\_if\_anagram( 'Know' , 'Now' ) )
def check\_if\_anagram( first\_word, second\_word) :
first\_word = first\_word. lower( )
second\_word = second\_word. lower( )
return sorted ( first\_word) == sorted ( second\_word)
print ( check\_if\_anagram( "testinG" , "Testing" ) )
print ( check\_if\_anagram( "Here" , "Rehe" ) )
print ( check\_if\_anagram( "Know" , "Now" ) )
▍90、使用itertools中的count计算元素的数量
from itertools
import count
my\_vowels = \[ 'a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U' \]
current\_counter = count( )
string = "This is just a sentence."
for i in string:
if i in my\_vowels:
print ( f"Current vowel: { i} " )
print ( f"Number of vowels found so far: { next ( current\_counter) } " )
Current vowel: i
Number of vowels found so far: 0
Current vowel: i
Number of vowels found so far: 1
Current vowel: u
Number of vowels found so far: 2
Current vowel: a
Number of vowels found so far: 3
Current vowel: e
Number of vowels found so far: 4
Current vowel: e
Number of vowels found so far: 5
Current vowel: e
Number of vowels found so far: 6
▍91、对字符串或列表的元素进行次数排序
collections模块的Counter(),默认情况下是不会根据元素的频率对它们进行排序的。
result = Counter( \[ 1 , 2 , 3 , 2 , 2 , 2 , 2 \] )
print ( result)
print ( result. most\_common( ) )
map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。
▍92、查找列表中出现频率最高的元素
my\_list = \[ '1' , 1 , 0 , 'a' , 'b' , 2 , 'a' , 'c' , 'a' \]
print ( max ( set ( my\_list) , key= my\_list. count) )
▍93、copy()和deepcopy()的区别
浅拷贝: 拷贝父对象,但是不会拷贝对象的内部的子对象。 深拷贝: 拷贝父对象. 以及其内部的子对象。 下面是一个copy()的例子。
first\_list = \[ \[ 1 , 2 , 3 \] , \[ 'a' , 'b' , 'c' \] \]
second\_list = first\_list. copy( )
first\_list\[ 0 \] \[ 2 \] = 831
print ( first\_list)
print ( second\_list)
import copy
first\_list = \[ \[ 1 , 2 , 3 \] , \[ 'a' , 'b' , 'c' \] \]
second\_list = copy. deepcopy( first\_list)
first\_list\[ 0 \] \[ 2 \] = 831
print ( first\_list)
print ( second\_list)
▍94、访问字典中不存在的键时,避免报错
my\_dictonary = { "name" : "Name" , "surname" : "Surname" }
print ( my\_dictonary\[ "age" \] )
KeyError: 'age'
可以通过使用defaultdict(),代码将不会报错。
my\_dictonary = defaultdict( str )
my\_dictonary\[ 'name' \] = "Name"
my\_dictonary\[ 'surname' \] = "Surname"
print ( my\_dictonary\[ "age" \] )
▍95、构建迭代器
class OddNumbers :
def \_\_iter\_\_( self) :
self. a = 1
return self
def \_\_next\_\_( self) :
x = self. a
self. a += 2
return x
odd\_numbers\_object = OddNumbers( )
iterator = iter ( odd\_numbers\_object)
print ( next ( iterator) )
print ( next ( iterator) )
print ( next ( iterator) )
▍96、删除列表的重复项
my\_set = set ( \[ 1 , 2 , 1 , 2 , 3 , 4 , 5 \] )
print ( list ( my\_set) )
▍97、打印模块的安装位置
import pandas
print ( pandas)
▍98、使用not in检查一个值是否在列表中
odd\_numbers = \[ 1 , 3 , 5 , 7 , 9 \]
even\_numbers = \[ \]
for i in range ( 9 ) :
if i not in odd\_numbers:
even\_numbers. append( i)
print ( even\_numbers)
▍99、sort()和sorted()的区别
sort():对原始列表进行排序 sorted():返回一个新的排序列表
groceries = \[ 'milk' , 'bread' , 'tea' \]
new\_groceries = sorted ( groceries)
print ( new\_groceries)
print ( groceries)
groceries. sort( )
print ( groceries)
▍100、使用uuid模块生成唯一ID
import uuid
print ( uuid. uuid1( ) )
print ( uuid. uuid4( ) )
总结
最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里] 】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西 ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析 ③ 100多个Python实战案例,学习不再是只会理论 ④ 华为出品独家Python漫画教程,手机也能学习
可以扫描下方二维码领取【保证100%免费 】