发现了一个十分不错的Python社区–PythonTab:Python中文开发者社区门户,上面有不错的教程及python高阶修炼方法,从中挑了几个体验了一番。
1.filter–函数过滤序列python函数每日一讲 - filter函数过滤序列 - python函数每日一讲: Python函数|Python类库 (pythontab.com)
- 语法
filter(function, iterable)
- 参数
function – 判断函数
iterable --可迭代对象
-
返回值
符合条件的新列表
文章中的例子:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
list = [1,2,4,6,8,9]
def is_gt_5(num):
return num > 5
new_list = filter(is_gt_5, list)
print(new_list)
[out] [6, 8, 9]
- 高级用法 1. 过滤非数字字符
>>> name = ``'pythontab.com 2018'``>>> filter(str.isdigit, name)``'2018'
2. 过滤数字>>> filter(str.isalpha, name)``'pythontabcom'
3. 保留数字和小数点>>> filter(lambda char: char ``in` `‘0123456789.’, name) ``'.2018'
返回遍历序列的下标或键以及元素
(1)使用enumerate遍历字典
test = {'A': 1, 'B': 2, 'C': 3}
for key, value in enumerate(test):
print(f"{key}: {values}")
0: A 1: B 2: C
(2)使用enumerate遍历列表
l = [1, 2 ,3]
for index, value in enumerate(l):
print(index, value)
0 1 1 2 2 33.dir函数
不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
>>>import numpy >>>dir(numpy)
截取部分输出
['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', ... ...
(2)对自定义的类使用
class User:
def __init__(self):
self.name = 'Jason'
self.account = '12345'
def login(self):
pass
>>>dir(User)
输出
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'login']4.delattr(object, name)
删除object对象名为name的属性。这个函数的用法还是挺简单的。与之相同的还有getattr(object, name)和setattr(object, name)
class User:
def __init__(self, name, passwd):
self.name = name
self.passwd = passwd
if __name__ == '__main__':
user1 = User('Jason', '123')
result = getattr(user1, 'name')
print(result)
print(user1.passwd)
setattr(user1, 'passwd', '12345')
print(getattr(user1, 'passwd'))
Jason 123 12345
等价于
if __name__ == '__main__':
user1 = User('Jason', '123')
result = user1.name
print(result)
print(user1.passwd)
user1.passwd = '12345'
print(user1.passwd)
5.format函数 – 字符串格式化
偷懒一下,原文章:format函数字符串格式化入门
Python爱好者一定要去这个社区逛逛!



