help(list.__dict__)
dir(list.__dict__)
dir(list)
分类 "Python" 下的文章
问题:有一个list,希望将里面的元素相加,获得它的和
解决:使用reduce,逐次操作list里的每项,接收参数2个,返回一个结果
方法:
a = [1,3,5,4,2,3]
reduce(lambda x,y:x+y, a)
注:在python3中使用时需要from functools import reduce否则会报错:NameError: name 'reduce' is not defined
拓展:
计算5的阶乘
reduce(lambda x,y:x*y, range(1,6))
问题:如何知道一个元素在list中出现的次数
解决:使用list的count方法
方法:
a = [2,3,4,5,6,3,2,4,2,'2']
a.count(2)
输出3
问题:在python中如何保留两位小数
解决:使用round或'%.2f'
方法:
a = round(97/3, 2)
python2中a为32.0,python3中为32.33
b = '%.2f' % (97/3)
python2中b为‘32.00’,python3中为‘32.33’
问题:python如何删除list中的元素
解决:使用del或者remove()方法
方法:
a = [1, 232, 43, 55, 3, 6, 5, 7, 3, 5, 6, 'a', 44]
a.remove(3)
输出a:[1, 232, 43, 55, 6, 5, 7, 3, 5, 6, 'a', 44]
del a[3] 或者 del(a[3])
输出a:[1, 232, 43, 6, 5, 7, 3, 5, 6, 'a', 44]