python內置函數

python內置函數:python

經常使用的內置函數,如:input()、print()、len()、type()、str()、tuple()、set()、dict()、list()函數

l='asdfgwert3r'
print(sorted(l)) #排序
print(all([1,2,3,4,'']))#若是list裏面都爲真的就返回true
print(any([0,0,0,1]))#判斷可迭代的對象裏面的值是否有一個爲真
print(bin(10))#十進制轉二進制
print(bool(0))#把一個對象轉換成布爾類型
print(chr(66))#打印數字對應的ascii
print(ord('B'))#打印字符串對應的ascii碼
print(dict(a=1,b=2))#轉換字典code

print(dir(s))#打印傳入對象的可調用方法對象

print(max([12,3,4,5]))#取最大值
min([12,3,4,5])blog

print(round(3.1415926,3))#取幾位小數排序

print(eval('[]'))#執行python代碼,只能執行簡單的,定義數據類型和運算
print(exec('def a():pass'))#執行復雜的python代碼ip

eval舉例:ci

執行簡單的代碼字符串

s1 = '1+2'input

print(eval(s))#執行運算1+2

s = "[1,2,3,4]"  #定義一個字符串s

print(eval(s))  #將s轉成list

s = "{'id':1,'name':'lll'}"  #定義一個字符串s

print(eval(s))  #將s轉成字典

exec舉例:

執行復雜的、字符串形式的python代碼

func_str = '''
def fun():
return 'func_name'
''' #定義一個字符串
exec(func_str)
res = fun() #若是不用exec,不能調用fun()函數;
print(res)

filter()舉例:

l = [12,3,12,2,1,2,35]
def t(i):
if i%3==0:
return True
print(list(filter(t,l))) #循環過濾數據;保存結果爲True的數據

map()舉例:

l = [12,3,12,2,1,2,35]
def t(i):
if i%3==0:
return True
print(list(map(t,l))) #循環調用數據,返回函數執行結果

同時循環多個list,用zip():

l1 =[1,2,3]l2 = ['a','b','c']l3 = ['a','b','c','d']for k1,k2,k3 in zip(l1,l2,l3):  #同時循環多個lst,匹配不上的就無論了    print(k1,k2,k3)
相關文章
相關標籤/搜索