Python基础(一)

  • 常用工具和库简要介绍
  • Python基本概念

科学计算常用工具和库

  • NumPy-数学计算基础库:N维数组、线性代数计算、傅立叶变换、随机数等。
  • SciPy-数值计算库:线性代数、拟合与优化、插值、数值积分、稀疏矩阵、图像处理、统计等。
  • SymPy-符号运算
  • Pandas-数据分析库:数据导入、整理、处理、分析等。
  • Matplotlib-绘图库:绘制二维图形和图表。
  • scikit-learn: Machine Learning in Python
  • Beautiful soup:爬虫工具
  • nltk:Natural Language Toolkit
  • Chaco-交互式图表
  • TVTK-数据的三维可视化
  • Mayavi-更方便的可视化
  • VPython-制作3D演示动画
  • OpenCV-图像处理和计算机视觉
  • Cython-Python转C的编译器:编写高效运算扩展库的首选工具
  • BioPython-生物科学

Python基本概念与操作

  • 整数(int): 32位, 2 >>> type(2)
  • 长整数(long): 无限精度, 3L >>> type(3L)
  • 浮点数: 52.3E-4,E标记表示10的幂。
  • 复数: (-5+4j)和(2.3-4.6j)。

变量赋值

a,b,c=1,2,3
a=[1,2,3];b,c,d=a
a=(1,2,3);b,c,d=a

字符串

  • 反斜杠 </kbd>

1
2
3
4
>>> a = '12345\
... 67890'
>>> print a
1234567890
  • 分片

1
2
3
4
5
>>> s = 'abcdefghijklmnop'
>>> s[1:10:2]
'bdfhj'
>>> s[::2]
'acegikmo'
  • 修改

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> s = 'spam'
>>> s[0] = 'x'
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> s = 'spam'
>>> s = s + 'SPAM'
>>> s
'spamSPAM'
>>> s = s[:4] + 'OK!' + s[-1]
>>> s
'spamOK!M'
  • 格式化

1、在%操作符左侧放置一个需要进行格式化的字符串,这个字符串带有一个或多个嵌入的转换目标,都以%开头,如%d、%f等
2、在%操作符右侧放置一个对象(或多个,在括号内),这些对象会被插入到左侧格式化字符串的转换目标的位置上

1
2
3
4
5
6
>>> bookcount = 10
>>> "there are %d books"%bookcount
'there are 10 books‘

"That is %d %s bird!" % (1, 'dead')
'That is 1 dead bird!'

常用函数

  • eval - 字符串转化

将字符串str当成有效的表达式来求值并返回计算结果。

1
2
3
4
eval('12')
# 12
eval('12 + 3')
# 15
  • ord, chr

ord函数: 将单个字符转换为对应的ASCII数值(整数)。
chr函数: 可以将一个整数转换为对应的字符。

1
2
3
4
ord('a')
# 97
chr(97)
# 'a'
  • range

1
2
3
4
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(0, 15, 5)
[0, 5, 10]

内置模块

  • Random

1
2
3
4
5
6
7
import random
>>> random.random()
0.33452758558893336
>>> random.randint(1, 10)
5
>>> random.choice(['a', 'b', 'c'])
'c'

字典

  • 创建

1
2
3
4
>>> tel = {'jack':4098, 'shy':4139}
>>> tel['gree'] = 4127
>>> tel
{'gree': 4127, 'jack': 4098, 'shy': 4139}
  • 查询

1
2
>>> tel['jack']
4098
  • 删除 del,pop

1
2
3
>>> del tel['shy']
>>> tel
{'gree': 4127, 'jack': 4098}
1
2
3
4
5
>>> tel = {'gree': 5127, 'irv': 4127, 'jack': 4098, 'pang': 6008}
>>> tel.pop('gree')
5127
>>> tel
{'irv': 4127, 'jack': 4098, 'pang': 6008}
  • update

1
2
3
4
5
6
>>> tel
{'gree': 4127, 'irv': 4127, 'jack': 4098}
>>> tel1 = {'gree':5127, 'pang':6008}
>>> tel.update(tel1)
>>> tel
{'gree': 5127, 'irv': 4127, 'jack': 4098, 'pang': 6008}
  • 帮助

1
help(dict)

控制语句

if语句

  • 基础结构
1
2
3
4
5
6
if <test1>:
<statements1>
elif <test2>:
<statements2>
else:
<statements3>
  • 例1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#coding:utf-8
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block starts here
print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
print 'No, it is a little higher than that' # Another block
# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach here
print 'Done'
# This last statement is always executed, after the if statement is executed
  • 例2
1
2
3
4
5
6
7
8
9
10
if choice == 'spam':
print 1.25
elif choice == 'ham':
print 1.99
elif choice == 'eggs':
print 0.99
elif choice == 'bacon':
print 1.10
else:
print 'bad choice'
  • 字典简化if语句
1
2
3
4
5
6
choice = 'ham'
dic = {'spam': 1.25,
'ham': 1.99,
'eggs': 0.99,
'bacon': 1.10}
print dic[choice]

While语句

  • 基础结构
1
2
3
4
while <test>:       #Loop test
<statements1> #Loop body
else: #Optional else
<statements2> #Run if didn't exit loop with break
  • 例1
1
2
3
4
5
a = 0
b = 10
while a<b:
print a
a = a + 1
  • 例2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little lower than that'
else:
print 'No, it is a little higher than that'
else:
print 'The while loop is over.'
# Do anything else you want to do here
print 'Done'

for语句

  • 基本结构1
1
2
3
4
for <target> in <object>:#Assign object items to target
<statements> #Repeated loop body:use target
else:
<statements> #If we didn't hit a 'break'
  • 基本结构2
1
2
3
4
5
6
7
8
9
10
11
12
for <target> in <object>:#Assign object items to target
<statements> #Repeated loop body:use target
if <test>: break #Exit loop now, skip else
if <test>: continue #Go to top of loop now
else:
<statements> #If we didn't hit a 'break'
for <target> in <object>:#Assign object items to target
<statements> #Repeated loop body:use target
if <test>: break #Exit loop now, skip else
if <test>: continue #Go to top of loop now
else:
<statements> #If we didn't hit a 'break'
  • 例1
1
2
3
4
5
6
7
def text_create():
path = 'E:/python/'
for text_name in range(1,11):
with open (path + str(text_name) + '.txt','w') as text:
text.write(str(text_name+9))
text.close()
print('Done‘)
  • 例2
1
2
3
4
5
6
file = open('E:/python/1.txt')
try:
data = file.read()
finally:
file.close()
print data
1
2
3
with open('E:/python/1.txt') as file:
data = file.read()
print data

break/continue

1
2
3
4
5
6
7
8
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print 'Input is of sufficient length'
continue
# Do other kinds of processing here...

Data Structures

List Methods

list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x)
Return the number of times x appears in the list.

list.sort(cmp=None, key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()
Reverse the elements of the list, in place.

An example that uses most of the list methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> a.pop()
1234.5
>>> a
[-1, 1, 66.25, 333, 333]
-------------文章结束啦 ฅ●ω●ฅ 感谢您的阅读-------------