1、 数字中的相关函数
数学函数
(cmp函数在python3.0已经被删除,使用 (x>y)-(x<y) 替换。)
import math
print(abs(-10)) #10
print(math.ceil(4.1)) #5
print(math.exp(1)) #2.718281828459045
print(math.fabs(-1)) #1.0
print(math.floor(4.1)) #4
print(math.log(100,10))#2.0
print(math.log10(100)) #2.0
print(max(1,2,3,4,5)) #5
print(min(1,2,3,4,5)) #1
print(math.modf(6.66)) #(0.6600000000000001, 6.0)
print(math.pow(2,3)) #8.0
print(round(6.666,2)) #6.67
print(math.sqrt(4)) #2.0
随机数函数
import random
print(random.choice([1,2,3,4,5]))#choice() 方法返回一个列表,元组或字符串的随机项
print(random.randrange(100,1000,2))#返回一个随机数,随机数在100~1000范围内且不包括一千,从100开始每次递增2
print(random.random())#随机生成下一个实数,它在[0,1)范围内
list=[5.6,3,9,1]
random.shuffle(list) #将序列的所有元素随机排序
print(list)
print(random.uniform(1,5)) #uniform() 方法将随机生成下一个实数,它在 [x, y] 范围内
运行结果:
三角函数
2、列表的内置函数&方法
列表函数
list1 =[1,2,3,4,5,6]
tuple =(1,2,3,4)
print(len(list1)) #输出6
print(max(list1)) #输出6
print(min(list1)) #输出1
print(list(tuple)) #输出[1,2,3,4],list() 方法用于将元组转换为列表。
#注:元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中
列表方法
list1 =[1,2,3,4,5,6,6]
list2 =['aaa','bbb',12,13]
list3 =[1,5,9,6,4,20]
list1.append(7)
print(list1) #[1, 2, 3, 4, 5, 6, 6, 7]
print(list1.count(6)) #2
list1.extend(list2)
print(list1) #[1, 2, 3, 4, 5, 6, 6, 7, 'aaa', 'bbb', 12, 13]
print(list1.index('aaa')) #8
print(list1.pop()) #13
print(list1) #[1, 2, 3, 4, 5, 6, 6, 7, 'aaa', 'bbb', 12]
list1.remove(4)
print(list1) #[1, 2, 3, 5, 6, 6, 7, 'aaa', 'bbb', 12]
list1.reverse()
print(list1) #[12, 'bbb', 'aaa', 7, 6, 6, 5, 3, 2, 1]
list3.sort(reverse=True)
print(list3) #[20, 9, 6, 5, 4, 1],rverse=True时降序
list3.sort(reverse=False)
print(list3) #[1, 4, 5, 6, 9, 20],reverse=False时升序,list.sort()默认为升序
3、元组内置函数
tuple1=(1,2,3,4,5,6)
list1=[1,2,3]
print(len(tuple1)) #6
print(max(tuple1)) #6
print(min(tuple1)) #1
print(tuple(list1))#(1, 2, 3)
4、字典内置函数&方法
字典函数
dict1 = {'a':'banana','b':'orange',10:1}
print(len(dict1)) #3
print(str(dict1)) #{'a': 'banana', 'b': 'orange', 10: 1}
print(type(dict1)) #<class 'dict'>
字典内置方法
(python3删除了has_key()方法)
dict1 ={'a':'banana','b':'apple',10:5}
dict3 ={'aa':1,'bb':2}
tuple1=(1,2,3,4,5)
print(dict1.copy()) #{'a': 'banana', 'b': 'apple', 10: 5}
dict2=dict.fromkeys(dict1,6)
print(dict2) #{'a': 6, 'b': 6, 10: 6}
print(dict1.get('b')) #apple
print(dict1.items()) #dict_items([('a', 'banana'), ('b', 'apple'), (10, 5)])
print(dict1.keys()) #dict_keys(['a', 'b', 10])
print(dict1.setdefault('c')) #None
dict1.update(dict3)
print(dict1) #{'a': 'banana', 'b': 'apple', 10: 5, 'c': None, 'aa': 1, 'bb': 2}
print(dict1.values()) #dict_values(['banana', 'apple', 5, None, 1, 2])
print(dict1.pop('aa')) #1
print(dict1) #{'a': 'banana', 'b': 'apple', 10: 5, 'c': None, 'bb': 2}
print(dict1.popitem()) #('bb', 2)
print(dict1) #{'a': 'banana', 'b': 'apple', 10: 5, 'c': None}
5、 字符串内置函数
字符串函数有很多,我就不举例子啦~