1.枚举对象
>>>s=["a","b","c"]
>>>for i,v in enumerate(s,1):
print(i,v)
1 a
2 b
3 c
>>>for i,v in enumerate(s,4):
print(i,v)
4 a
5 b
6 c
2.查看变量所占字节数
>>>import sys
>>>a={'a':1,'b':2.0}
>>>sys.getsizeof(a)
232
>>>sys.getsizeof(1)
28
>>>sys.getsizeof(2)
28
>>>sys.getsizeof(2.0)
24
>>>sys.getsizeof(3.1415926)
24
>>>b={}
>>>sys.getsizeof(b)
64
>>>sys.getsizeof('hhh')
52
>>>sys.getsizeof('n')
50
>>>sys.getsizeof('bb')
51
3.过滤器 在函数中设置过滤条件,迭代元素,保留返回值为True的元素
filter(function, iterable) (判断函数,可迭代对象)
而python2.7返回列表,python3.x返回迭代器对象
>>>fill=filter(lambda x:x>10,[1,11,67,89,4,33,13,6])
>>>list(fill)
[11, 67, 89, 33, 13]
>>>a=[7,9,33,0,-8,-23,-5,45]
>>>fill_2=filter(lambda x:x<=0,a)
>>>list(fill_2)
[0, -8, -23, -5]
>>>a
[7, 9, 33, 0, -8, -23, -5, 45]
def filter_false(lst):
return list(filter(bool,lst))
r=filter_false([None,0,False,'',[],'\0','0','ok',[3,4]])
print(r)
def is_even(n):
return n%2==0
lst=list(filter(is_even,[1,2,3,4,5,6,7,8,9,10]))
print(lst)
4.合并字典
>>>{**{'a':1,'b':2},**{'c':3}}
{'a': 1, 'b': 2, 'c': 3}
>>>d_1={'菠萝':13.5,'梨子':9.5,'樱桃':23.6}
>>>d_2={'黄瓜':2.4,'西红柿':3.5}
>>>d_3={**d_1,**d_2}
>>>d_3
{'菠萝': 13.5, '梨子': 9.5, '樱桃': 23.6, '黄瓜': 2.4, '西红柿': 3.5}
>>>d_4={'李子':19}
>>>d_3={**d_1,**d_2,**d_4}
>>>d_3
{'菠萝': 13.5, '梨子': 9.5, '樱桃': 23.6, '黄瓜': 2.4, '西红柿': 3.5, '李子': 19}
5.运用operator模块实现计算器
import operator
def calculator(num1,num2,sign):
return{
'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv,
'**':operator.pow
}[sign](num1,num2)
result=calculator(8,2,'**')
print(result)
import operator
def add_or_sub(num1,num2,sign):
return(operator.add if sign=='+'else operator.sub)(num1,num2)
result=add_or_sub(867,351,'-')
print(result)
6.去最求平均
def score_mean(lst):
lst.sort()
lst2=lst[1:len(lst)-1]
return round(sum(lst2)/len(lst2),1)
lst=[9,10,9.8,8.8,9.1,8.6]
result=score_mean(lst)
print(result)
7.列表等分
from math import ceil
def divide(lst,size):
if size<=0:
return [lst]
return [lst[size*i:(i+1)*size]for i in range(0,ceil(len(lst)/size))]
lst=[1,3,5,7,9,2,4,6,8,10]
print(divide(lst,3))
8.找出长度最长的列表
def max_length(*lst):
return max(*lst,key=lambda v:len(v))
r=max_length([1,2,3],[6,7],['hello','insist','persist','act'],['okaylalala'])
print(r)
9.找出出现次数最多的列表元素
def top1(lst):
return max(lst,default='列表为空',key=lambda a:lst.count(a))
lst=[1,2,3,4,1,1,2,2,7,5,2]
r=top1(lst)
print(f'{lst}中出现次数最多的元素是{r}')
10.找出多个表中最大的一个元素
def max_lists(*lst):
return max(max(*lst,key=lambda v:max(v)))
r=max_lists([1,2,3],[6,7,8],[9,10])
print(r)
|