大家好,我是小F~
目前Python可以说是非常流行,在目前的编程语言中,Python的抽象程度是最高的,是最接近自然语言的,很容易上手。
你可以用它来完成很多任务,比如数据科学、机器学习、Web开发、脚本编写、自动化等。
下面,小F就给大家分享100个Python小技巧,帮助大家更好的了解和学习Python。
▍1、for循环中的else条件
这是一个for-else方法,循环遍历列表时使用else语句。
下面举个例子,比如我们想检查一个列表中是否包含奇数。
那么可以通过for循环,遍历查找。
numbers=[2,4,6,8,1]fornumberinnumbers:ifnumber%2==1:print(number)breakelse:print("Nooddnumbers")如果找到了奇数,就会打印该数值,并且执行break语句,跳过else语句。
没有的话,就不会执行break语句,而是执行else语句。
▍2、从列表中获取元素,定义多个变量
my_list=[1,2,3,4,5]one,two,three,four,five=my_list
▍3、使用heapq模块,获取列表中n个最大或最小的元素
importheapqscores=[51,33,64,87,91,75,15,49,33,82]print((3,scores))[15,33,33,49,51]
▍4、将列表中的所有元素作为参数传递给函数
我们可以使用*号,提取列表中所有的元素
my_list=[1,2,3,4]print(my_list)1234
如此便可以将列表中的所有元素,作为参数传递给函数
defsum_of_elements(*arg):total=0foriinarg:total+=ireturntotalresult=sum_of_elements(*[1,2,3,4])print(result)[2,3,4,5,6,7]
▍6、使用一行代码赋值多个变量
one,two,three,four=1,2,3,4
▍7、列表推导式
只用一行代码,便可完成对数组的迭代以及运算。
比如,将列表中的每个数字提高一倍。
numbers=[1,2,3,4,5]squared_numbers=[num*numfornuminnumbers]print(squared_numbers){'a':16,'b':25}▍8、通过Enum枚举同一标签或一系列常量的集合
枚举是绑定到唯一的常量值的一组符号名称(成员)。
在枚举中,成员可以通过身份进行比较,枚举本身可以迭代。
fromenumimportEnumclassStatus(Enum):NO_STATUS=-1NOT_STARTED=0IN_PROGRESS=1COMPLETED=2print(_)2
▍9、重复字符串
name="Banana"print(name*4)Trueprint(1xandx10){'name':'Fan','location':'Guangdong,Guangzhou','surname':'Xiao'}▍12、查找元组中元素的索引
books=('Atomichabits','Egoistheenemy','Outliers','Mastery')print(('Mastery'))[1,2,3]string="[[1,2,3],[4,5,6]]"my_list=string_to_list(string)print(my_list)-2print((subtract(3,1)))-2print((subtract(b=3,a=1)))HelloWorldprint("Hello",="")print("World")words,with,commas,in,between▍17、打印多个值,在每个值之间使用自定义分隔符
print("29","01","2022",sep="/")name@▍18、不能在变量名的开头使用数字
four_letters="abcd"thisdoesn’twork
这是Python的变量命名规则。
▍19、不能在变量名的开头使用运算符
+variable="abcd"thisdoesn'twork
这个确实挺神奇的。
▍21、在变量名的任何地方使用下划线
a______b="abcd"thisalsoworks
这并不意味着,你可以无限使用,为了代码的易读性,还是需要合理使用。
▍22、使用下划线分割数值较大的数字
print(1_000_000_000)1234567
如此,看到一大堆数字时,也能轻松阅读。
▍23、反转列表
my_list=['a','b','c','d']my_()print(my_list)ThisTsse
▍25、反向切片
my_string="Thisisjustasentence"print(my_string[10:0:-1])Taketwostepsforwardprint(my_string[10:0:-2])isjustasentenceprint(my_string[:3])1.5print(3//2)比较两个值print(first_list==second_list)是否指向同一内存print(first_listissecond_list)True
▍29、合并字典
dictionary_one={"a":1,"b":2}dictionary_two={"c":3,"d":4}merged={**dictionary_one,**dictionary_two}print(merged)Truesecond="ab"print(firstsecond)False▍32、使用id()查找变量的唯一id
print(id(1))4325776656print(id("string"))4325215472print(id(1))4325215536print(id(1))4422282544name="fatos"print(id(name))4482699712("Beijing")print(id(cities))4352726176my_(5)print(id(my_set))Positive▍38、使用sorted()检查2个字符串是否为相同
defcheck_if_anagram(first_word,second_word):first_word=first_()second_word=second_()returnsorted(first_word)==sorted(second_word)print(check_if_anagram("testinG","Testing"))Trueprint(check_if_anagram("Know","Now"))65print(ord("B"))66print(ord("a"))['a','b','c']▍41、获取字典的值
dictionary={"a":1,"b":2,"c":3}values=()print(list(values)){1:'a',2:'b',3:'c'}▍43、将布尔值转换为数字
print(int(False))1.0
▍44、在算术运算中使用布尔值
x=10y=12result=(x-False)/(y*True)print(result)Falseprint(bool(3))Trueprint(bool("string"))True▍46、将值转换为复数
print(complex(10,2))[2,3,4,5,6]
▍48、Lambda函数只能在一行代码中
无法通过多行代码,来使用lambda函数。
comparison=lambdax:ifx3:print("x3")else:print("xisnotgreaterthan3")报错。

▍49、Lambda中的条件语句应始终包含else语句
comparison=lambdax:"x3"ifx3
运行上面的代码,报错。

这是由于条件表达式的特性,而不是lambda的导致的。
▍50、使用filter(),获得一个新对象
my_list=[1,2,3,4]odd=filter(lambdax:x%2==1,my_list)print(list(odd))[1,2,3,4]
▍51、map()返回一个新对象
map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。
my_list=[1,2,3,4]squared=map(lambdax:x**2,my_list)print(list(squared))[1,2,3,4]
▍52、range()的step参数
fornumberinrange(1,10,3):print(number,="")012range_with_no_zero(3)True
▍55、可以在同一个作用域内多次定义一个方法
但是,只有最后一个会被调用,覆盖以前。
defget_address():return"Firstaddress"defget_address():return"Secondaddress"defget_address():return"Thirdaddress"print(get_address())62000
▍57、检查对象的内存使用情况
importsysprint(("bitcoin"))6print(get_sum(1,2,3,4,5))28▍59、使用super()或父类的名称调用父类的初始化
使用super函数调用父类的初始化方法。
classParent:def__init__(self,city,address):==addressclassChild(Parent):def__init__(self,city,address,university):super().__init__(city,address)=universitychild=Child('PekingUniversity','FudanUniversity','TsinghuaUniversity')print()TsinghuaUniversity▍60、在类中使用+操作符
在两个int数据类型之间使用+运算符时,将得到它们的和。
而在两个字符串数据类型之间使用它时,会将其合并。
print(10+1)字符串相加
这个就是操作符重载,你还可以在类中使用(__add__)。
classExpenses:def__init__(self,rent,groceries):==groceriesdef__add__(self,other):returnExpenses(+,+)april_expenses=Expenses(1000,200)may_expenses=Expenses(1000,300)total_expenses=april_expenses+may_expensesprint(total_)500
▍61、在类中使用和==操作符
下面定义一个操作重载示例(操作符),使用__lt__方法。
classGame:def__init__(self,score):=scoredef__lt__(self,other):=Game(1)second=Game(2)print(firstsecond)'Rectanglewitharea=12'
▍63、交换字符串中字符的大小写
string="Thisisjustasentence."result=()print(result)True
▍65、检查字符串是否都是字母或数字
name="Password"print(())Falsename="S3cur3P4ssw0rd"print(())True
▍66、检查字符串是否都是字母
string="Name"print(())Falsestring="P4ssw0rd"print(())"Thisisasentencewith"string="thishereisasentence…..,,,,aaaaasd"print((".,dsa"))First▍68、检查字符串是否为数字
string="seven"print(())Truestring="5a"print(())False
▍69、检查字符串是否为中文数字
Falseprint(())Falsestring="10PythonTips"print(())Falseprint(())string="PYTHON"print(())4print(numbers[-4])['first','second','third']print(mixed_tuple[0])2
▍74、使用slice()获取元素
使用slice()获取最后n个元素。
my_list=[1,2,3,4,5,6,7,8,9,10]slicing=slice(-4,None)print(my_list[slicing])4
使用slice()做切片任务。
string="DataScience"slice_object=slice(5,None)print(string[slice_object])3
▍76、获取元组中元素的索引
my_tuple=('a',1,'f','a',5,'a')print(my_('f'))(1,4,7,10)▍78、通过索引获取子元组
my_tuple=(1,2,3,4,5,6,7,8,9,10)print(my_tuple[3:])[]my_set={1,2,3}my_()print(my_set){}▍80、合并集合
使用union()方法,返回一个新集合。
first_set={4,5,6}second_set={1,2,3}print(first_(second_set)){1,2,3,4,5,6}▍81、在函数里输出结果
defis_positive(number):print("Positive"ifnumber0else"Negative")Congratulations!Youhavepassedalloftheexams.▍83、在一个if语句中,至少满足多个条件中的一个
math_points=40biology_points=78physics_points=56history_points=72my_conditions=[math_points50,biology_points50,physics_points50,history_points50]ifany(my_conditions):print("Congratulations!Youhavepassedalloftheexams.")else:print("Iamsorry,butitseemsthatyouhavetorepeatatleastoneexam.")Trueprint(bool(""))Falseprint(bool(set([])))Falseprint(bool({"a":1}))Falseprint(bool(None))False▍87、在函数中使用全局变量
在函数无法直接修改全局变量的值。
string="string"defdo_nothing():string="insideamethod"do_nothing()print(string)insideamethod
▍88、计算字符串或列表中元素的数量
使用collections中的Counter计算字符串或列表中元素的数量。
fromcollectionsimportCounterresult=Counter("Banana")print(result)Counter({1:5,2:1,3:1,4:1,5:1,6:1})▍89、检查2个字符串是否为相同
可以使用Counter()方法。
fromcollectionsimportCounterdefcheck_if_anagram(first_string,second_string):first_string=first_()second_string=second_()returnCounter(first_string)==Counter(second_string)print(check_if_anagram('testinG','Testing'))Trueprint(check_if_anagram('Know','Now'))Trueprint(check_if_anagram("Here","Rehe"))False▍90、使用itertools中的count计算元素的数量
fromitertoolsimportcountmy_vowels=['a','e','i','o','u','A','E','I','O','U']current_counter=count()string="Thisisjustasentence."foriinstring:ifiinmy_vowels:print(f"Currentvowel:{i}")print(f"Numberofvowelsfoundsofar:{next(current_counter)}")输出如下。
Currentvowel:iNumberofvowelsfoundsofar:0Currentvowel:iNumberofvowelsfoundsofar:1Currentvowel:uNumberofvowelsfoundsofar:2Currentvowel:aNumberofvowelsfoundsofar:3Currentvowel:eNumberofvowelsfoundsofar:4Currentvowel:eNumberofvowelsfoundsofar:5Currentvowel:eNumberofvowelsfoundsofar:6
▍91、对字符串或列表的元素进行次数排序
collections模块的Counter(),默认情况下是不会根据元素的频率对它们进行排序的。
fromcollectionsimportCounterresult=Counter([1,2,3,2,2,2,2])print(result)[(2,5),(1,1),(3,1)]
map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。
▍92、查找列表中出现频率最高的元素
my_list=['1',1,0,'a','b',2,'a','c','a']print(max(set(my_list),key=my_))[[1,2,831],['a','b','c']]print(second_list)[[1,2,831],['a','b','c']]print(second_list)1print(next(iterator))5
▍96、删除列表的重复项
my_set=set([1,2,1,2,3,4,5])print(list(my_set))module'torch'from'/Users/'
▍98、使用notin检查一个值是否在列表中
odd_numbers=[1,3,5,7,9]even_numbers=[]foriinrange(9):ifinotinodd_numbers:even_(i)print(even_numbers)new_groceries=['bread','milk','tea']print(new_groceries)groceries=['bread','milk','tea']print(groceries)
▍100、使用uuid模块生成唯一ID
UUID代表唯一标识符。
importuuid308490b6-afe4-11eb-95f7-0c4de9a0c5af93bc700b-253e-4081-a358-24b60591076a