1.通过函数取差。举例:返回有差别的列表元素
from math import floordef difference_by ( a, b, fn) : b = set ( map ( fn, b) ) return [ i for i in a if fn( i) not in b]
print ( difference_by( [ 2.1 , 1.2 ] , [ 2.3 , 3.4 ] , floor) )
2.一行代码调用多个函数
def add ( a, b) : return a + b
def subtract ( a , b) : return a - b
a, b = 4 , 5
print ( ( subtract if a> b else add) ( a, b) )
3.检查列表是否有重复项:有重复项就返回True,无重复项就返回
def has_duplicate ( lst) : return len ( lst) != len ( set ( lst) )
x = [ '公共开发' , '实验室' , 'python' ]
y = [ '公共开发' , '实验室' , 'python' , 'python' ]
4.合并两个字典
def merge_dictionaries ( a, b) : return { ** a, ** b}
a = { 'x' : 1 , 'y' : 2 }
b = { 'y' : 3 , 'z' : 4 }
print ( merge_dictionaries( a, b) )
5.将两个列表转化为字典
def to_dictionary ( keys, values) : return dict ( zip ( keys, values) )
keys = [ 'a' , 'b' , 'c' ]
values = [ 2 , 3 , 4 ]
print ( to_dictionary( keys, values) )
6.使用枚举
lst = [ 'a' , 'b' , 'c' , 'd' ]
for index, value in enumerate ( lst) : print ( 'value' , value, 'index' , index)
7.执行某代码所花费的时间
import time
start_time = time. time( )
a = 2023
b = 2022
c = a - b
print ( c)
end_time = time. time( )
total_time = end_time - start_time
print ( 'Time:' , total_time)
8.Try else
try : print ( int ( '你' ) )
except : print ( '有异常发生,请检查:int没法直接强制转换字符"你"' )
else : print ( 'try成功才会执行此处' )
9.列表出现的频率最多元素
def most_frequent ( lst2) : return max ( lst2, key= lst2. count)
lst1 = [ 'Python' , 'Python' , '公共开发' , '公共开发' , '公共开发' , '12345678' ]
print ( most_frequent( lst1) )
10.筛选出最长的字符串
def most_max_length ( lst2) : return max ( lst2, key= len )
lst1 = [ 'Python' , 'Python' , '公共开发' , '公共开发' , '公共开发' , '12345678' ]
print ( most_max_length( lst1) )
11.快速修改列表字符元素为整形
def change_int ( lst) : lst2 = list ( map ( str , lst) ) return lst2
lst = [ 1 , 2 , 3 , 4 , 5 , 6 ]
print ( change_int( lst) )
12.回文序列检测:所谓回文序列指的是字符串与反向字符串是否相等。
from re import sub
def palindrome ( string) : s = sub( '[\W_]' , '' , string. lower( ) ) print ( s) return s == s[ : : - 1 ]
print ( palindrome( 'ta co cat' ) )
13.字典默认值:通过 Key 取对应的 Value 值,可以通过以下方式设置默认值。如果 get() 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None。
d = { 'a' : 1 , 'b' : 2 }
print ( d. get( 'c' , 3 ) )