您的位置:首页 > 编程语言 > Python开发

python 学习记录1

2014-07-18 21:26 148 查看

快速反转列表

>>> animals = ['lion', 'tigher', 'leopard', 'wolf']
>>> animals[::-1]
['wolf', 'leopard', 'tigher', 'lion']

字符串find与index区别

同:找到后都返回位置索引号,
不同:find 找不到返回 -1, index 找不到返回

>>> s = 'haowells'
>>> s.find('z')
-1
>>> s.index('z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.find('a')
1
>>> s.index('a')
1


字典的setdefault 设置key的默认值

>>> d = {}
>>> d.setdefault('a')
>>> d
{'a': None}
>>> d.setdefault('b', set())
set([])
>>> d
{'a': None, 'b': set([])}
>>> d.setdefault('c', {})
{}
>>> d
{'a': None, 'c': {}, 'b': set([])}


has_key 与hasattr

has_key在python3 已经废除,用in 替代
>>> d = {}
>>> d['a'] = 1
>>> d.has_key['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'has_key'
>>> 'a' in d
hasattr(内置函数) 判断一个对象是否存在某属性
>>> dir(d)
['__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute
__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '_
_reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'cle
ar', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
>>> hasattr(d, 'get')
True
>>> hasattr(d, 'has_key')
False


getattr 通过获取类对象的函数名字符串, 返回该函数调用

以下命令等同于执行os.getcwd()

>>> import os
>>> func = getattr(os, 'getcwd')
>>> func()
'C:\\Windows\\System32'


获取当前时间的二种方法

>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2014, 7, 18, 15, 7, 41, 713000)
>>> now.time()
datetime.time(15, 7, 41, 713000)
>>> datetime.time(now)
datetime.time(15, 7, 41, 713000)

获取当前python shell 环境安装的模块列表

模块列表包括了导入的第三方模块

>>> help('modules')

Please wait a moment while I gather a list of all available modules...

BaseHTTPServer      antigravity         itertools           requests
Bastion             anydbm              json                rexec


* 在函数参数解包(unpack) 中的用法

>>> def func1(**kwargs):
...     for k in kwargs:
...             print k, kwargs[k]
...
>>> d1 = dict(name='john', age=30)
>>> d1
{'age': 30, 'name': 'john'}
>>> func1(**d1)
age 30
name john

>>> def func1(**kwargs):
...     for k in kwargs:
...             print k, kwargs[k]
...
>>> d1 = dict(name='john', age=30)
>>> d1
{'age': 30, 'name': 'john'}
>>> func1(**d1)
age 30
name john
在3.0 中,还可以用于赋值
>>> first, *rest = (1,2,3,4)
>>> first
1
>>> rest
[2, 3, 4]
>>> first, *mid, last = [1,2,3,4]
>>> first
1
>>> mid
[2, 3]
>>> last
4


合并两个字典并赋值给第3个字典

第一个方法z 返回None, 第二方法使用dict(dict.items())
>>> x = {'a':1, 'b': 2}
>>> y = {'b':2, 'c': 3}
>>> z = x.update(y)
>>> x
{'a': 1, 'c': 3, 'b': 2}
>>> print z
None
>>> z = dict(x.items() + y.items())
>>> z
{'a': 1, 'c': 3, 'b': 2}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python