Python基础知识笔记

Python基础知识笔记


运行一个脚本后再进入交互终端 python -i

使用-i参数

1
2
3
4
5
$ echo "#!/usr/bin/env python
import sys" > test.py

$ python -i test.py
>>> sys.path

print的内容禁止转义 \

使用 r' '使单引号中的所有字符禁止转义

1
2
3
4
5
>>> print 'x\ny\tz'
x
y z
>>> print r'x\ny\tz'
x\ny\tz

打印多行 ‘’’…’’’

使用\n输入多行时可能不太好阅读,可以通过''' '''三引号的方式来输出多行

1
2
3
4
5
6
7
>>> print '''line one
... line two
... line three
... '''
line one
line two
line three

常量 PI

在Python中的常量也是一个变量,只不过为了显示这是个常量,约定俗成用大写表示常量
在Python中没有任何机制保证大写的变量不会被更改!

1
>>> PI = 3.1415926

字符串与数字间的转换(ASCII)

1
2
3
4
>>> ord('L')
76
>>> chr(76)
'L'

在Python中使用Unicode编码

1
2
3
4
5
6
7
8
>>> '中文'
'\xe4\xb8\xad\xe6\x96\x87'
>>> u'中文'
u'\u4e2d\u6587'
>>> print u'中文'
中文
>>> print u'\u4e2d\u6587'
中文

Unicode与禁止转义连用 print ur’…’

1
2
3
4
5
6
>>> print u'中\t文'
中 文
>>> print ur'中\t文'
中\t文
>>> ur'中\t文'
u'\u4e2d\\t\u6587'

Unicode与utf-8字符编码间的转换

Unicode 2 UTF-8

1
2
3
4
5
6
7
8
>>> u'ABC'
u'ABC'
>>> u'ABC'.encode('utf-8')
'ABC'
>>> u'中文'
u'\u4e2d\u6587'
>>> u'中文'.encode('utf-8')
'\xe4\xb8\xad\xe6\x96\x87'

UTF-8 2 Unicode

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> '\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
u'\u4e2d\u6587'
>>> print '\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
中文
>>> print u'\u4e2d\u6587'
中文
>>>
>>> 'ABC'.decode('utf-8')
u'ABC'
>>> print 'ABC'.decode('utf-8')
ABC
>>> print u'ABC'
ABC

Python文件中使用中文的声明 print u’…’

1
2
3
#!/usr/bin/env python
#coding=utf-8
print u'中文'

字符串格式化(占位符)

常见的占位符:

  • %d 整数
  • %f 浮点数
  • %s 字符串
1
2
3
4
>>> print 'Hi %s' % 'ps'
Hi ps
>>> print 'Hi %s, I have %d questions to ask you' % ('ps', 59)
Hi ps, I have 59 questions to ask you

对Unicode字符串进行占位时,字符编码需要前后保持一致

1
2
>>> print u'Hi %s, I have %d questions to ask you' % (u'ps', 59)
Hi ps, I have 59 questions to ask you

对占位符转义%%–>’%’

1
2
3
4
5
6
>>> print "update %d%" % 59
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: incomplete format
>>> print "update %d%%" % 59
update 59%

列表

1
2
3
>>> testlist = ['Apple', 'Microsoft', 'Samaung']
>>> testlist
['Apple', 'Microsoft', 'Samaung']

取值 list[index]

列表中最后一个元素的位置是len(testlist) - 1 or testlist[-1]

以此类推,倒数第二个元素是testlist[-2]

1
2
3
4
5
6
7
8
9
10
11
12
>>> testlist
['Apple', 'Microsoft', 'Samaung']
>>> len(testlist)
3
>>> len(testlist) - 1
2
>>> testlist[len(testlist) - 1]
'Samaung'
>>> testlist[-1]
'Samaung'
>>> testlist[-2]
'Microsoft'

追加 append(value)

1
2
3
4
5
>>> testlist
['Apple', 'Microsoft', 'Samaung']
>>> testlist.append('lastvalue')
>>> testlist
['Apple', 'Microsoft', 'Samaung', 'lastvalue']

插入 insert(index, value)

1
2
3
4
5
>>> testlist
['Apple', 'Microsoft', 'Samaung', 'lastvalue']
>>> testlist.insert(1, 'secondvalue')
>>> testlist
['Apple', 'secondvalue', 'Microsoft', 'Samaung', 'lastvalue']

删除末尾及指定位置的元素 pop(index)

1
2
3
4
5
6
7
8
9
10
>>> testlist
['Apple', 'secondvalue', 'Microsoft', 'Samaung', 'lastvalue']
>>> testlist.pop()
'lastvalue'
>>> testlist
['Apple', 'secondvalue', 'Microsoft', 'Samaung']
>>> testlist.pop(1)
'secondvalue'
>>> testlist
['Apple', 'Microsoft', 'Samaung']

替换元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#直接覆盖
>>> testlist
['Apple', 'Microsoft', 'Samaung']
>>> testlist[2] = 'Google'
>>> testlist
['Apple', 'Microsoft', 'Google']
``

## 二维数组

```python
>>> testlist = [['iPhone', 'iPad', 'iMac'], 'Microsoft', 'Google']
>>> testlist
[['iPhone', 'iPad', 'iMac'], 'Microsoft', 'Google']
>>> len(testlist)
3
>>> testlist[0][1]
'iPad'

元组

单个元素的元组

1
2
3
4
5
6
7
8
9
10
>>> testtuple = ('apple')
>>> testtuple
'apple'
>>> type(testtuple)
<type 'str'>
>>> testtuple = ('apple', )
>>> testtuple
('apple',)
>>> type(testtuple)
<type 'tuple'>

“可变元组”

一般情况下元组是不可变的数据结构,如果需要实现让元组可变,可以在元组中加入列表来实现

1
2
3
4
5
6
7
8
9
10
>>> testtuple = (['iPhone', 'iPad', 'iMac'], 'Microsoft', 'Google')
>>> testtuple
(['iPhone', 'iPad', 'iMac'], 'Microsoft', 'Google')
>>> testtuple[0].append('iPod')
>>> testtuple
(['iPhone', 'iPad', 'iMac', 'iPod'], 'Microsoft', 'Google')
>>> testtuple[0][2] = 'MBP'
>>> testtuple
(['iPhone', 'iPad', 'MBP', 'iPod'], 'Microsoft', 'Google')
#元组的指向并没有变,所以这个元组可以认为仍然没有变化,变的是元组中list的元素

if判断语句

基础语法

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> results = 100
>>> if results < 0 or results > 100:
... print "OMG!!!"
... elif 0 <= results < 60:
... print "Fail!!!"
... elif 60 <= results < 80:
... print "OK!!!"
... elif results >= 80 and results <=100:
... print "good!!!"
... else:
... print "Impossible!!!"
...
good!!!

简写

只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False

1
2
3
4
5
6
7
8
9
>>> x = ''
>>> x
''
>>> if x:
... print 'not null'
... else:
... print 'null'
...
null

循环

for…in…

1
2
3
4
5
6
7
>>> testtuple = (['iPhone', 'iPad', 'iMac'], 'Microsoft', 'Google')
>>> for t in testtuple:
... print t
...
['iPhone', 'iPad', 'iMac']
Microsoft
Google

while

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> start = 0
>>> end = 9
>>> while True:
... print start
... start = start + 1
... if start > end:
... break
...
0
1
2
3
4
5
6
7
8
9

raw_input

num = raw_input('please input a num:')

字典

基础语法

1
2
3
>>> p = {'apple':'pages', 'microsoft':'word', 'google':'docs'}
>>> p['apple']
'pages'

检查元素是否包含在字典中

1
2
3
4
>>> p = {'apple':'pages', 'microsoft':'word', 'google':'docs'}
>>> p['apple']
'pages'
>>> 'apple' in p
1
2
3
4
5
#查找不到元素会返回None空
>>> p.get('google')
'docs'
>>> p.get('baidu')
>>>

删除一个key

1
2
3
4
>>> p.pop('google')
'docs'
>>> p
{'apple': 'pages', 'microsoft': 'word'}

in关键字

1
2
3
4
5
6
7
8
9
10
11
#判断一个元素是否包含在一个字典中
>>> p = {'apple':'pages', 'microsoft':'word', 'google':'docs'}
>>> p['apple']
'pages'
>>> 'apple' in p
True
#判断一个元素是否包含在一个列表中
>>> testlist
[['iPhone', 'iPad', 'iMac'], 'Microsoft', 'Google']
>>> 'Google' in testlist
True

集合

  • 可变集合(set)
  • 不可变集合(frozenset)

集合的基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
>>> s = set([1, 2, 3])
>>> s
set([1, 2, 3])
>>> type(s)
<type 'set'>

## 访问集合

集合是无序的,所以不能对集合创建索引或切片的操作,只能循环遍历或使用innot in来访问或判断集合元素

```python
>>> s = set([1, 2, 3, 4])
>>> s
set([1, 2, 3, 4])
>>> 2 in s
True
>>> 5 in s
False
>>> for i in s:
... print i
...
1
2
3
4

集合中的元素不能重复,集合会自动过滤掉重复的元素

1
2
3
4
5
6
>>> s.add(4)
>>> s
set([1, 2, 3, 4])
>>> s.add(4)
>>> s
set([1, 2, 3, 4])

删除集合中的元素

1
2
3
>>> s.remove(2)
>>> s
set([1, 3, 4])

交集与并集

1
2
3
4
5
6
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
set([2, 3])
>>> s1 | s2
set([1, 2, 3, 4])

子集(真子集)超集(真超集)

子集包含集合本身,真子集不包含本身!如(1,2)的子集有:空集,(1),(2),(1,2).而真子集有:空集,(1),(2)没有(12)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#子集(<=)  真子集(<)
>>> set('shop') < set('bookshop')
True
>>> set('shop') <= set('bookshop')
True
>>> set('bookshop') < set('bookshop')
False
>>> set('bookshop') <= set('bookshop')
True
#超集(>=) 真超集(>)
>>> set('bookshop') > set('shop')
True
>>> set('bookshop') >= set('shop')
True
>>> set('bookshop') > set('bookshop')
False
>>> set('bookshop') >= set('bookshop')
True

异或

1
2
3
4
5
6
7
8
>>> s1
set([1, 2, 3])
>>> s2
set([2, 3, 4])
>>> s1 ^ s2
set([1, 4])
>>> s1.symmetric_difference(s2)
set([1, 4])

差补/相对补集

1
2
3
4
5
6
7
8
9
>>> s1
set([1, 2, 3])
>>> s2
set([2, 3, 4])
set([1, 4])
>>> s1 - s2
set([1])
>>> s2 -s1
set([4])

集合的应用: 去重

强制类型转换

字典

字典 2 字符串

1
2
3
4
5
>>> d = {'a':1, 'b':2}
>>> d
{'a': 1, 'b': 2}
>>> print type(str(d)), str(d)
<type 'str'> {'a': 1, 'b': 2}

字典 2 元组

1
2
3
4
5
6
7
>>> d = {'a':1, 'b':2}
>>> d
{'a': 1, 'b': 2}
>>> print tuple(d)
('a', 'b')
>>> print tuple(d.values())
(1, 2)

字典 2 列表

1
2
3
4
5
6
7
>>> d = {'a':1, 'b':2}
>>> d
{'a': 1, 'b': 2}
>>> print list(d)
['a', 'b']
>>> print list(d.values())
[1, 2]

元组

元组 2 字符串

1
2
3
4
5
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> print type(str(t)), str(t)
<type 'str'> (1, 2, 3)

元组 2 列表

1
2
3
4
5
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> print type(list(t)), list(t)
<type 'list'> [1, 2, 3]

元组 2 集合

1
2
3
4
5
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> print type(set(t)), set(t)
<type 'set'> set([1, 2, 3])

元组不能转成字典

列表

列表 2 字符串

1
2
3
4
5
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> print type(str(l)), str(l)
<type 'str'> [1, 2, 3]

列表 2 元组

1
2
3
4
5
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> print type(tuple(l)), tuple(l)
<type 'tuple'> (1, 2, 3)

列表 2 集合

1
2
3
4
5
>>> l = [1, 2, 3]
>>> l
[1, 2, 3]
>>> print type(set(l)), set(l)
<type 'set'> set([1, 2, 3])

列表不能转成字典

字符串

字符串 2 列表

1
2
3
4
5
6
7
>>> s = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> s
'[[1,2], [3,4], [5,6], [7,8], [9,0]]'
>>> print list(s)
['[', '[', '1', ',', '2', ']', ',', ' ', '[', '3', ',', '4', ']', ',', ' ', '[', '5', ',', '6', ']', ',', ' ', '[', '7', ',', '8', ']', ',', ' ', '[', '9', ',', '0', ']', ']']
>>> print type(eval(s)), eval(s)
<type 'list'> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]

字符串 2 字典

1
2
3
4
5
>>> s = "{1: 'a', 2: 'b'}"
>>> s
"{1: 'a', 2: 'b'}"
>>> print type(eval(s)), eval(s)
<type 'dict'> {1: 'a', 2: 'b'}

字符串 2 元组

1
2
3
>>> s = "([1,2], [3,4], [5,6], [7,8], (9,0))"
>>> print type(eval(s)), eval(s)
<type 'tuple'> ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))

字符串 2 集合

1
2
3
>>> s = "test"
>>> print type(set(s)), set(s)
<type 'set'> set(['s', 'e', 't'])