现在的位置: 首页 > 综合 > 正文

Python基本使用方法记录

2018年02月20日 ⁄ 综合 ⁄ 共 1019字 ⁄ 字号 评论关闭

1、文件迭代器

for line in open('filename', 'r'):

print line

2、并行遍历:

>>>L1=[1,2,3,4]

>>>L2=[5,6,7,8]

>>>zip(L1,L2)

[(1,5),(2,6),(3,7),(4,8)]

可以用for并行访问zip(L1,L2)中元素

for (x,y) in zip(L1,L2):

printf x,y


也可以并行访问多个文件,以两个文件为例:

for (line1,line2) in zip(open('filename1','r'), open('filename2', 'r')):

print line1

print line2

3、列表解析

3.1 简单解析

lines = [line.rstrip() for line in open('filename')]

lines是列表,其中元素师filename文件中的每行

3.2 扩展列表解析

可以在for循环中结合一个if分句过滤不合格的字符

lines=[line.rstrip() for line open('filename') if line[0] == 'p']

lines中保留了只有首字母为p的项

4、引用

4.1

python中变量名引用一个对象,如a=3表示a指向对象的指针,所以

b=a

a='aaa'

后b的值依然为3,a只是从新指向了对象'aaa'的指针,不会改变3所在的内存值

4.2

可以通过列表,字典,集合等数据结构改变变量值

L1=[1,2,3]

L1[0]=20

后L1的值为20,2,3

5 python中搜索顺序

导入模块时的搜索路径为:

1)、程序的主目录

2)、PYTHONPATH目录

3)、标准链接库目录

4)、任何.pth文件内容

6 numpy声明二维数组

>>> from numpy import * 
>>> d = zeros((3,4))  
>>> d
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

或者

ones( (2,3), dtype=int16 )
array([[1, 1, 1],
       [1, 1, 1]], dtype=int16)

6 从python数组中找出特定元素

>>> ss_id
array([20705, 20705, 15549, 15549, 15549, 15549])
从ss_id中找出20705元素,如果不存在则返回空数组
>>> ss_id[ss_id==20705]
array([20705, 20705])

抱歉!评论已关闭.