码迷,mamicode.com
首页 > 其他好文 > 详细

通用内置函数

时间:2021-04-13 12:31:01      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:from   迭代   变量   集合   map   turn   页码   stat   随机   

# 通用内置函数

## pow()

### 求次幂

a1 = pow(2,3)  #等同与2**3
print(a1)
结果:8


## ord()

### 字符转换位数字

print(ord("a"))  #对照ascll码
结果:97


## chr()

### 将数字转换成unicode格式的字符,可以用来生成随机数

print(chr(80))
结果:P
例2:

import random
def get_radomcode(length=6):
    data = []
    for item in range(length):
        v = chr(random.randint(65,90))
        data.append(v)

    return  "".join(data)

a = get_radomcode()
print(a)
结果:随机生成6位字母


## abs()

### 取绝对值

a = -9.1
print(abs(a))
结果:9.1


## sorted()

### 列表元组排序返回列表

a = [2,5,8,9,10,50,1]
a1 = sorted(a,reverse=True)  #False是升序,true降序
print(a1)
结果:[50, 10, 9, 8, 5, 2, 1]


## sum()

### 求列表元组中的所有值的和

a = (2,5,8,9,10,50,1)
a1 = sum(a)
print(a1)
结果:85


## min()

### 取列表,元组中最小值

a = (2,5,8,9,10,50,1)
a1 = min(a)
print(a1)
结果:1


## max()

### 取列表,元组中最大值

a = [2,5,8,9,10,50,1]
a1 = max(a)
print(a1)
结果:50


## len()

### 计算变量长度

## id()

### 获取变量的内村地址

## str()

### 转换位字符串

## input()

### 输入

## isinstance()

### 判断类型

x1 = 123.45
x2 = 123

print(isinstance(x1, float))
结果:
True
列2
x1 = 123.45
x2 = 123

print(isinstance(x2, int))
结果:
True

列子2:

#判断变量类型的函数
 2 def typeof(variate):
 3     type=None
 4     if isinstance(variate,int):
 5         type = "int"
 6     elif isinstance(variate,str):
 7         type = "str"
 8     elif isinstance(variate,float):
 9         type = "float"
10     elif isinstance(variate,list):
11         type = "list"
12     elif isinstance(variate,tuple):
13         type = "tuple"
14     elif isinstance(variate,dict):
15         type = "dict"
16     elif isinstance(variate,set):
17         type = "set"
18     return type
9# 返回变量类型
def getType(variate):
    arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
    vartype = typeof(variate)
    if not (vartype in arr):
        return "未知类型"
    return arr[vartype]
结果:
浮点


print(getType(1.2))

列3:

 #判断变量类型的函数
 2 def typeof(variate):
 3     type1 = ""
 4     if type(variate) == type(1):
 5         type1 = "int"
 6     elif type(variate) == type("str"):
 7         type1 = "str"
 8     elif type(variate) == type(12.3):
 9         type1 = "float"
10     elif type(variate) == type([1]):
11         type1 = "list"
12     elif type(variate) == type(()):
13         type1 = "tuple"
14     elif type(variate) == type({"key1":"123"}):
15         type1 = "dict"
16     elif type(variate) == type({"key1"}):
17         type1 = "set"
18     return type1
19 # 返回变量类型
20 def getType(variate):
21     arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
22     vartype = typeof(variate)
23     if not (vartype in arr):
24         return "未知类型"
25     return arr[vartype]


## encode()

### 字符串编码,将unicode对象编成其它编码的字符串

#字符串编码,可以UTF-8 GBK GB2312 等

x1 = "林明均已|经9岁了,听明说喜欢|编程,但是上明课注意|力还是不集中。"
x2 = x1.encode(encoding="utf-8")
print(x2)

x3 = x2.decode(encoding="utf-8")
print(x3)
结果:
b‘\xe6\x9e\x97\xe6\x98\x8e\xe5\x9d\x87\xe5\xb7\xb2|\xe7\xbb\x8f9\xe5\xb2\x81\xe4\xba\x86\xef\xbc\x8c\xe5\x90\xac\xe6\x98\x8e\xe8\xaf\xb4\xe5\x96\x9c\xe6\xac\xa2|\xe7\xbc\x96\xe7\xa8\x8b\xef\xbc\x8c\xe4\xbd\x86\xe6\x98\xaf\xe4\xb8\x8a\xe6\x98\x8e\xe8\xaf\xbe\xe6\xb3\xa8\xe6\x84\x8f|\xe5\x8a\x9b\xe8\xbf\x98\xe6\x98\xaf\xe4\xb8\x8d\xe9\x9b\x86\xe4\xb8\xad\xe3\x80\x82‘
林明均已|经9岁了,听明说喜欢|编程,但是上明课注意|力还是不集中。



## decode()

### 字符串解码,将其它编码的字符串解码成指定编码(世界通用位unicode,内存中运算)

#解码字符串,utf-8  bgk  gb2312

x1 = "林明均已|经9岁了,听明说喜欢|编程,但是上明课注意|力还是不集中。"
x2 = x1.encode(encoding="utf-8")
print(x2)

x3 = x2.decode(encoding="utf-8")
print(x3)
结果:
b‘\xe6\x9e\x97\xe6\x98\x8e\xe5\x9d\x87\xe5\xb7\xb2|\xe7\xbb\x8f9\xe5\xb2\x81\xe4\xba\x86\xef\xbc\x8c\xe5\x90\xac\xe6\x98\x8e\xe8\xaf\xb4\xe5\x96\x9c\xe6\xac\xa2|\xe7\xbc\x96\xe7\xa8\x8b\xef\xbc\x8c\xe4\xbd\x86\xe6\x98\xaf\xe4\xb8\x8a\xe6\x98\x8e\xe8\xaf\xbe\xe6\xb3\xa8\xe6\x84\x8f|\xe5\x8a\x9b\xe8\xbf\x98\xe6\x98\xaf\xe4\xb8\x8d\xe9\x9b\x86\xe4\xb8\xad\xe3\x80\x82‘
林明均已|经9岁了,听明说喜欢|编程,但是上明课注意|力还是不集中。


## int()

### 转换为整形

x1 = "0b0101"  #这是个字符串类型
x2 = int(x1,base=2)  #base的值是指定由什么类型的数转换为整数,如果根据X1定,16进制就写16
print(x2)

结果:5


## float()

### 强制转换位浮点型

## hex()

### 强制转换位16进制0x1a格式

## bin()

### 强制转换位二进制0b1010格式

#IP转换位二进制和十进制


ip = "192.168.100.8"
ip_list = ip.split(".")
print(ip_list)
result =[]
for item in ip_list:
    bitem = bin(int(item))
    print(bitem,type(bitem))
    qbitem =bitem[2:]   #切片去除0b
    if len(qbitem)<8:
        qbitem = "0"*(8-len(qbitem))+qbitem   #去除0b后不够8位前面补0
    result.append(qbitem)
print("".join(result))  #把二进制拼接
print(int("".join(result),base=2))  #二进制转换十进制
结果:
[‘192‘, ‘168‘, ‘100‘, ‘8‘]
0b11000000 <class ‘str‘>
0b10101000 <class ‘str‘>
0b1100100 <class ‘str‘>
0b1000 <class ‘str‘>
11000000101010000110010000001000
3232261128



## bool()

### 强制转换位布尔型

## type()

### 获取变量类型

## print()

### 输出不换行可以用end=" "

for item in range(10):
    print(item,end=" ")
结果:
0 1 2 3 4 5 6 7 8 9 


### 打印后跳回起始位置"\r"

for item in range(10):
    print(item\r,end="")
结果:
9


实例2:
#打印进度条

import os
file_size = os.stat("vidio1.mp4").st_size
print(file_size)

chunk_size = 0
with open("vidio1.mp4","rb") as f1, open("vidio2.mp4","wb") as f2:
    while chunk_size<file_size:
        chunk_date = f1.read(1024)
        chunk_size+=len(chunk_date)
        # print(chunk_size)
        f2.write(chunk_date)
        val = int(chunk_size/file_size*100)
        # result1 = "%d%%\r" %result
        print("%s%%\r" %val,end="")


### 输出换行"\n"

## super()

## divmod(x,y)

### 对x除y,返回元组模和余数,常用做分页处理

a,b = divmod(10,3)
print(a,b)
结果:3 1


例子2:
#分页显示

info_list = []
for item in range(1,580):
    info = "你打开的是电影页面的第%s也" %item
    info_list.append(info)

totle_count = len(info_list)
page_count = 10
a,b = divmod(totle_count,page_count)
if b>0:
    a+=1
print(a)
while True:
    index = int(input("请输入页码数:"))
    if index<1 or index>a:
        print("输入页码不合法,必须输入1~%s" %a)
    else:
        display_info = info_list[(index-1) * page_count:index * page_count]
        for item in display_info:
            print(item)
结果:输入数字每10条显示


## map()

### 对一个可变参数修改生成另一个列表,常用批量修改一个列表

#一下列表中各个元素加100
a = [1,2,3,4,5,6]
a1 = map(lambda x:x+100 ,a)
print(a1)
print(list(a1))
结果:
<map object at 0x000000000287BE48>
[101, 102, 103, 104, 105, 106]


## filter()

### 过滤一个列表中不符合条件的元素

a = [1,"ad","发大水",4,5,6]
a1 = filter(lambda x:True if type(x)==int else False ,a) #循环列表每个元素,当元素位True把值添加到新列表中,False是弃掉
print(a1)
print(list(a1))
结果:[1, 4, 5, 6]


## reduce()

### 对参数序列中元素进行累积,前面两个结果运算后的得结果与第三个元素运算

from functools import reduce

a = ["a","b","c","d"]   #必须可迭代对象
a1 = reduce(lambda x,y:x+y,a) #
print(a1)
print(list(a1))
结果:
abcd
[‘a‘, ‘b‘, ‘c‘, ‘d‘]


*XMind - Trial Version*

通用内置函数

标签:from   迭代   变量   集合   map   turn   页码   stat   随机   

原文地址:https://www.cnblogs.com/shalaotou/p/14651128.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!