- 对数组做迭代过程中,有时我们既想使用内容又想知道该内容在数组中的下标,这时可以使用enumerate(iterable, start=0),如:
list=[2,3,0,2,7]
for index,val in enumerate(list,start=0):
if index%2 != 0 and (val != 0 or val!=0.0):
print(val)
使用range,len也可以:
for i in range(0,len(arr)):
if i%2 !=0:
print arr[i]
- 日期时间对象和字符串互转
dt = datetime.datetime.strptime("2015-11-30",'%Y-%m-%d')
dt_str= datetime.datetime.strftime(dt, '%Y-%m-%d')
dt = datetime.datetime.today() - datetime.timedelta(5)
- 浮点数保留指定位数的小数,以四舍五入形式:
round(2.3333,3)
- 字典合并
方法一
>>> dict1={"a":"c", "b":"d"}
>>> dict2={"c":"c", "b":"d"}
>>> dictMerged1=dict(dict1.items()+dict2.items())
>>> dictMerged1
{'a': 'c', 'c': 'c', 'b': 'd'}
方法二
>>> dictMerged2=dict(dict1, **dict2)
>>> dictMerged2
{'a': 'c', 'c': 'c', 'b': 'd'}
方法二会比方法一更加高效
5. 几个内置函数
map,reduce,zip,filter,