1. 函数的知识
-
eval()函数常见作用有:
-
计算字符串中有效的表达式,并返回结果
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" b = eval(a) print(b) #[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] a = "{1:'xx',2:'yy'}" c = eval(a) print(c) #{1: 'xx', 2: 'yy'} a = "(1,2,3,4)" d = eval(a) print(d) #(1, 2, 3, 4)
-
将字符串转成相应的对象(如list、tuple、dict和string之间的转换)
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" b = eval(a) print(b) #[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]] a = "{1:'xx',2:'yy'}" c = eval(a) print(c) #{1: 'xx', 2: 'yy'} a = "(1,2,3,4)" d = eval(a) print(d) #(1, 2, 3, 4)
-
将利用反引号转换的字符串再反转回对象
list1 = [1,2,3,4,5] print(list1) #'[1, 2, 3, 4, 5]' type(list1) #<type 'str'> type(eval(list1)) #<type 'list'> a = eval(list1) print(a) #[1, 2, 3, 4, 5]
-
-
chr()函数的用法:
-
Chr(数值表达式),函数返回值类型为String,其数值表达式值取值范围为0~255。
print(chr(78)) #N
-
-
ord()函数的用法:
-
ord(“字符串”), 函数返回值类型为int类型。
print(ord("N")) #78
-
-
get()函数的用法:
-
get(key,default = None),返回指定键的值,如果值不在字典中返回默认值
mes = {"name":"张三","age":18} print(mes.get("name","找不到")) #张三 print(mes.get("money","找不到")) #找不到
-
-
divmod()函数的用法:
-
把除数和余数运算结果结合起来,返回一个包含商和余数的元组
x = 10 y = 3 print(divmod(x,y)) #(3, 1)
-
-
sort()和sorted()函数的用法:
-
对列表进行排序,可以进行倒序排序
list = [3,9,5,1,7] list.sort() print(list) #[1, 3, 5, 7, 9] print(sorted(list)) #[1, 3, 5, 7, 9] print(sorted(list,reverse = True)) #[9, 7, 5, 3, 1]
-
-
round()函数的用法:
-
方法返回浮点数x的四舍五入值
print(round(3.1415926,2)) #3.14 print(round(3.00023,2)) #3.0 print(round(3.14)) #3 print(round(3.94)) #4
-
-
type()函数的用法:
-
返回变量的类型
str = "helloworld" date = 12 print(type(str)) #<class 'str'> print(type(date)) #<class 'int'>
-
-
id()函数的用法:
-
返回变量内存地址
str = "helloworld" date = str print(id(str)) #1728268783472 print(id(date)) #1728268783472
-
-
random.randint()函数的作用:
-
随机返回一个数
import random # 从区间[a,b]之间随机返回一个整数,左闭右闭 data = random.randint(1,10) print(data) #9
-
-
items()函数的作用:
- items()函数以列表返回可遍历的(键, 值) 元组数组。
knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k, v) """ gallahad the pure robin the brave """
-
hex()函数的作用:
-
用于将10进制整数转换成16进制,以字符串形式表示
print(hex(255)) #0xff
-
-
oct()函数的作用:
-
将一个整数转换成8进制字符串
print(oct(–255)) #–0o377'
-
-
bin()函数的作用:
-
讲一个整数转换成2进制字符串
print(bin(10)) #0b1010'
-
-
capitalize()函数的作用:
-
将字符串的第一个字母变成大写,其余字母变为小写。
a = "alex" b = a.capitalize() print(a,end=",") print(b) #alex,Alex
-
-
isnumeric()函数的作用:
-
检测字符串是否只由数字组成
str ="Python语言程序设计" print(str.isnumeric()) #False
-
-
pow()函数的作用:
-
计算幂次方
print(pow(3,3)) #27
-
-
filter()函数的作用:
-
会将过滤函数依次作用于每一个过滤序列的元素,返回符合要求的过滤值
def f2(a): if a > 33: return True li = [11, 22, 33, 44, 55] res = filter(f2, li) print(list(res)) #[44,55]
-
-
all()函数的作用:
-
判断列表中的所有元素是否都为True
print(all([1,True,True])) #True
-
-
choice()函数额作用:
-
方法返回一个列表,元组或字符串的随机项。
from random import choice list = [1,2,3,4] print(choice(list)) #3
-