一, 列表
1,idle 使用 (Mac)
(1) 代码自动补全 tab
(2) 回退代码语句
control+p 上一个代码
control+n 下一个代码
2, 列表就像是数组
列表是完备的 python 集合对象
且 python 的变量标识符没有类型.
- >>> movies = ["The Holy Grail","The life of brian"]
- >>> print(movies)
- ['The Holy Grail', 'The life of brian']
- >>> print(movies[0])
- The Holy Grail
> 使用下标访问列表数据
(1) 列表操作
append() 列表末尾添加一个数据项
pop() 列表末尾删除数据
extend() 列表末尾添加一个数据集合
1>>>movie.extend(["GOD","The girl"])
remove() 列表中删除特定数据项
insert() 特定位置前插入数据
>>> movies.insert(0,"Man")
(2)python 列表可以包含混合类型的数据, 可以存储任意类型的数据.
3, 列表迭代
(1)for 目标标识符 in 列表名:
列表处理代码
- >>> for each_mv in movies1:
- print(each_mv)
列表处理代码必须在 for 循环下面缩进. 列表处理代码块称为 "组".
(2)while
while 使用时要考虑状态信息, 这就需要一个计数标识符.(for 不用考虑状态信息)
- >>> count=0
- >>> while count <len(movies1):
- print(movies1[count])
- count = count+1
(3) 建议使用 for, 尽量避免使用 while
4, 字符串引号使用
对于字符串可以使用双引号也可以使用单引号, 但一个字符串不能混合使用.
注: 在字符串中嵌入一个双引号...... 使用转义:\"
5, 标识符命名规范
字母或下划线开头, 剩余可以使用任意个字母字符, 数字和 / 或者下划线.
6,python 对大小写敏感
7, 嵌套列表
(1) 列表可以存储任何东西的集合, 列表中的列表.
每个列表都是一个列表项集合, 各列表项之间用逗号隔开, 另外列表要用中括号括起.
- >>> movies1104 = ["体会生活",2010,"the first man",2011,["zhangyimou",["panjinlian","women","china"]]]
- >>> print(movies1104[4][1][2])
- china
(2) 嵌套列表遍历
if 条件:
代码块
else:
代码块
- >>> for movies1104_each in movies1104:
- if isinstance(movies1104_each,list):
- for each1 in movies1104_each:
- if isinstance(each1,list):
- for each2 in each1:
- print(each2)
- else:
- print(each1)
- else:
- print(movies1104_each)
注:
查看 python BIF(内置函数) 的方式; 查看够功能用 help(某个 BIF)
>> dir(__builtins__)
isinstance(each1,list) 判断某个标识符是否包含某个人指定类型的数据.
8, 函数
python 函数用 def 语句定义. 如何创建函数?
def 函数名 (参数):
函数代码组
- >>> def print_mo (the_list):
- for each_item in the_list:
- if isinstance(each_item,list):
- print_mo(each_item)
- else:
- print(each_item)
- >>> print_mo(movies1104)
体会生活
- 2010
- the first man
- 2011
- zhangyimou
- women
- china
python3 默认递归深度不能超过 100.
python 使用缩进将语句归组在一起.
二, 共享你的代码: 函数模块
1, 注释
三重引号 """ 或是 #.
2,BIF
list() 工厂函数, 创建一个新的空列表.
range() 返回一个迭代器, 可以根据需要生成一个指定范围的数字.
enumerate() 创建成对数据的一个编码列表, 从 0 开始
int() 将一个字符串或一个数转为一个整数
next() 返回一个可迭代数据结构中的下一项.
3,range() 打印缩进指定数目的制表符
- >>> def print_mo (the_list,level):
- for each_item in the_list:
- if isinstance(each_item,list):
- print_mo(each_item,level+1)
- else:
- for tab_stop in range(level):
- print("\t",end="")
- print(each_item)
- >>> print_mo(movies1104,2)
体会生活
- 2010
- the first man
- 2011
- zhangyimou20 women
- china
三, 文件与异常: 处理错误
1,python 的基本输入机制是基于行的
open() 打开文件时, 会创建一个迭代器从文件向代码输入数据行, 一次传入一行数据. 标准流程 "打开 - 处理 - 关闭":
- the_file = open('test.txt')
- #处理代码木块
- the_file.close()
- >>> import os
- >>> os.getcwd()# 获取当前工作路径
- '/Users/qanfuhong/Documents'
- >>> os.chdir('/Users/qanfuhong/Desktop/HeadFirstPython/chapter3')# 切换当前工作路径
- >>> os.getcwd()
- '/Users/qanfuhong/Desktop/HeadFirstPython/chapter3'
- >>> data = open('sketch.txt')
- >>> print(data.readline(),end='')#readline() 从文件获取一个数据行
- Man: Is this the right room for an argument?
- >>> print(data.readline(),end ='')
- Other Man: I've told you once.
- >>> print(data.readline(),end ='')
- Man: No you haven't!
- >>> data.seek(0)# 返回文件起始位置
- 0
- >>> for each_line in data :
- print(each_line,end='')# 循环遍历, 将文件的数据按行打印
- Man: Is this the right room for an argument?
- Other Man: I've told you once.
- Man: No you haven't!
- Other Man: Yes I have.
- Man: When?
- Other Man: Just now.
- Man: No you didn't!
- Other Man: Yes I did!
- ......
- Man: Yes it is!
- >>>
2,split() 方法有可选参数
用于控制将数据行分解为多少个部分. 默认是将数据尽可能多的分解.
- >>>data = open('sketch.txt')
- >>>for each_line in data:
- (role,line_spoken) = each_line.split(":")
- print(role,end='')
- print('said:',end='')
- print(line_spoken,end='')
结果:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
Man said: No you haven't!
Other Man said: Yes I have.
each_line.split(':',1) 表示只将数据行分解为两部分.
3,find() 方法
寻找字符串的子串, 找不到则返回 - 1, 找到则返回子串在字符串的索引位置.
- >>> each_line = "i love you ,nana."
- >>> each_line.find(':')
- -1
- >>> each_line.find('nana')
- 12
附: 项目中使用到的一个 python 脚本
主要功能是将 sql 查询结果进行排序加工.
- #!/usr/bin/env python
- # coding: utf-8
- # In[3]:
- import numpy as np
- import pandas as pd
- import sys
- def generator30(filein,fileout):
- df = pd.read_csv(filein,sep = '\t',header = 0)
- df['advantage_user']=0
- df['sayhirate'][df['sayhirate'].isnull()]=0
- df['sayhirate'][df['sayhirate']>1]=1
- for (k1,k2),group in df.groupby(['age','province']):
- p30 = 1 + int(group.index.shape[0]*.3)
- df.loc[group.index[0:p30],'adavantage_user'] = 1
- df.loc[group.index[p30:],'adavantage_user'] = 0
- df[(df['adavantage_user']!=0) & (df['adavantage_user']!=1)]=-1
- df['adavantage_user'] = df['adavantage_user'].astype(int)
- df['sayhirate'] = (df['sayhirate']*10000).astype(int)
- df = df[['user_id','province','sex','age','sayhirate','adavantage_user']]
- df.to_csv(fileout,sep='\t',index=0)
- #filein, fileout 分别为输入文件路径, 输出文件路径
- infile = sys.argv[1]
- outfile = sys.argv[2]
- generator30(infile,outfile)
来源: http://www.bubuko.com/infodetail-2889814.html