python学习笔记(一):基础知识点
- defaultdict函数将所有值初始化为指定类型
from collections import defaultdict
a = defaultdict(int)
a[0]
''
- python按照引用传递
a = [1,2,3]
b = a
a.append(4)
b
[1, 2, 3, 4]
- isinstance函数检查对象是否为某个特定的类型
a = 7
isinstance(a, float)
False
- is用来判断两份引用是否指向同一个对象与 == 不同
a = [1,2,3]
b = a
c = list(a)
a is not c
True
- 字符串左边加上r表示字符应该按原本样子解释
s = r'e\\e'
print(s)
e\\e
- strftime将时间转化为字符串
- strptime将字符串转化为时间
from datetime import datetime
a = datetime.now()
a.strftime('%m/%d/%Y %H:%M')
'02/09/2018 21:07'
datetime.strptime('20091009', '%Y%m%d')
datetime.datetime(2009, 10, 9, 0, 0)
-
continue 进入下一个迭代
-
break 结束循环
-
pass 空操作
-
range可以用在for循环中,range始终返回迭代器
a = 0
for i in range(4):
a += i
a
6
- 三元表达式
x = 5
'positive' if x > 0 else 'negative'
'positive'
- 元组拆包
tup = (1, 2, 3)
a, b, c = tup
b
2
- count计算指定值的出现次数
a = (2,3,4,4,4,5)
a.count(4)
3
- insert、extend、pop与remove、del
- extend可以添加多个元素
b = ['a', 'b', 'c']
b.append('d')
b
['a', 'b', 'c', 'd']
b.pop(2)
b
['a', 'b', 'd']
b.insert(2, 'c')
b
['a', 'b', 'c', 'd']
b.remove('d')
b
['a', 'b', 'c']
b.extend(('d', 'e'))
b
['a', 'b', 'c', 'd', 'e']
del b[1]
b
-
python切片方式:数中间的空格
-
切片第二个冒号为步长
za = [1,2,3,4,5]
za[::2]
[1, 3, 5]
za[::-1]
[5, 4, 3, 2, 1]
- enumerate用法
aa = dict((v, i) for i, v in enumerate(b))
aa
{'e': 1, 'w': 0}
- 排序
sorted(range(4))
[0, 1, 2, 3]
list(reversed(range(4)))
[3, 2, 1, 0]
- zip
a = ['a','d']
b = ['w', 'e']
for i in zip(a, b):
print(i)
('a', 'w')
('d', 'e')
c = dict(zip(range(5), reversed(range(5))))
c
{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
- 字典的合并update()
c.update({'d' : 'ww'})
c
{0: 4, 1: 'ww', 2: 2, 3: 1, 4: 0, 5: 'ww', 'd': 'ww'}
- lambda函数
from collections import defaultdict
count = defaultdict(lambda:4)
count['w']
4
strings = ['foo', 'card', 'bar', 'aaaa', 'abab']
strings.sort(key = lambda x : len(set(list(x))))
strings
['aaaa', 'foo', 'abab', 'bar', 'card']
- 列表推导式
tuples = [(1,2,3), (4,5,6), (7,8,9)]
[x for tup in tuples for x in tup]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[[x for x in tup] for tup in tuples]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- 函数实际接受到的是一个元组*args,和一个字典**kwargs。
somedict = {'a' : 1, 'b' : 2}
for key in somedict:
print(key)
a
b