python 学习笔记之一

原文链接: http://www.cnblogs.com/hongfuqitian/p/10141929.html

一、列表

1、idle使用(Mac)

(1)代码自动补全 tab

(2)回退代码语句
  control+p 上一个代码
  control+n 下一个代码

2、列表就像是数组

  列表是完备的python集合对象
  且python的变量标识符没有类型。

1 >>> movies = ["The Holy Grail","The life of brian"]
2 >>> print(movies)
3 ['The Holy Grail', 'The life of brian']
4 >>> print(movies[0])
5 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 列表名:
列表处理代码

1 >>> for each_mv in movies1:
2 print(each_mv)

列表处理代码必须在for循环下面缩进。列表处理代码块称为“组”。

(2)while
while使用时要考虑状态信息,这就需要一个计数标识符。(for 不用考虑状态信息)

1 >>> count=0
2 >>> while count < len(movies1):
3 print(movies1[count])
4 count = count+1

(3)建议使用for,尽量避免使用while

4、字符串引号使用

对于字符串可以使用双引号也可以使用单引号,但一个字符串不能混合使用。
注:在字符串中嵌入一个双引号……使用转义:\”

5、标识符命名规范

字母或下划线开头,剩余可以使用任意个字母字符数字/或者下划线

6、python对大小写敏感

7、嵌套列表

(1)列表可以存储任何东西的集合,列表中的列表。
每个列表都是一个列表项集合,各列表项之间用逗号隔开,另外列表要用中括号括起。

1 >>> movies1104 = ["体会生活",2010,"the first man",2011,["zhangyimou",["panjinlian","women","china"]]]
2 >>> print(movies1104[4][1][2])
3 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() 打印缩进指定数目的制表符

 1 >>> def print_mo (the_list,level):
 2 
 3 for each_item in the_list:
 4 if isinstance(each_item,list):
 5 print_mo(each_item,level+1)
 6 else:
 7 for tab_stop in range(level):
 8 print("\t",end="")
 9 print(each_item)
10 
11 
12 >>> print_mo(movies1104,2)
13 
14 体会生活
15 2010
16 the first man
17 2011
18 zhangyimou20 women
21 china

三、文件与异常:处理错误

1、python的基本输入机制是基于行的


open()打开文件时,会创建一个迭代器从文件向代码输入数据行,一次传入一行数据。标准流程“打开-处理-关闭”:

1 the_file = open('test.txt')
2 
3 #处理代码木块
4 
5 the_file.close()
 1 >>> import os
 2 
 3 >>> os.getcwd()#获取当前工作路径
 4 '/Users/qanfuhong/Documents'
 5 
 6 >>> os.chdir('/Users/qanfuhong/Desktop/HeadFirstPython/chapter3')#切换当前工作路径
 7 
 8 >>> os.getcwd()
 9 '/Users/qanfuhong/Desktop/HeadFirstPython/chapter3'
10 
11 >>> data = open('sketch.txt')
12 
13 >>> print(data.readline(),end='')#readline()从文件获取一个数据行
14 
15 Man: Is this the right room for an argument?
16 
17 >>> print(data.readline(),end ='')
18 
19 Other Man: I've told you once.
20 >>> print(data.readline(),end ='')
21 Man: No you haven't!
22 
23 >>> data.seek(0)#返回文件起始位置
24 0
25 >>> for each_line in data :
26 print(each_line,end='')#循环遍历,将文件的数据按行打印
27 
28 Man: Is this the right room for an argument?
29 Other Man: I've told you once.
30 Man: No you haven't!
31 Other Man: Yes I have.
32 Man: When?
33 Other Man: Just now.
34 Man: No you didn't!
35 Other Man: Yes I did!
36 ……
37 Man: Yes it is!
38 >>>

2、split()方法有可选参数

用于控制将数据行分解为多少个部分。默认是将数据尽可能多的分解。

1 >>>data = open('sketch.txt')
2 >>>for each_line in data:
3 (role,line_spoken) = each_line.split(":")
4 print(role,end='')
5 print(' said: ',end='')
6 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,找到则返回子串在字符串的索引位置。

1 >>> each_line = "i love you ,nana."
2 
3 >>> each_line.find(':')
4 -1
5 >>> each_line.find('nana')
6 12

附:项目中使用到的一个python脚本

主要功能是将sql查询结果进行排序加工。

 1 #!/usr/bin/env python
 2 # coding: utf-8
 3 # In[3]:
 4 import numpy as np
 5 import pandas as pd
 6 import sys
 7 def generator30(filein,fileout):
 8 df = pd.read_csv(filein,sep = '\t',header = 0)
 9 df['advantage_user']=0
10 df['sayhirate'][df['sayhirate'].isnull()]=0
11 df['sayhirate'][df['sayhirate']>1]=1
12 for (k1,k2),group in df.groupby(['age','province']):
13 p30 = 1 + int(group.index.shape[0]*.3)
14 df.loc[group.index[0:p30],'adavantage_user'] = 1
15 df.loc[group.index[p30:],'adavantage_user'] = 0
16 df[(df['adavantage_user']!=0) & (df['adavantage_user']!=1)]=-1
17 df['adavantage_user'] = df['adavantage_user'].astype(int)
18 df['sayhirate'] = (df['sayhirate']*10000).astype(int)
19 df = df[['user_id','province','sex','age','sayhirate','adavantage_user']]
20 df.to_csv(fileout,sep='\t',index=0)
21 
22 #filein, fileout分别为输入文件路径,输出文件路径
23 infile = sys.argv[1]
24 outfile = sys.argv[2]
25 generator30(infile,outfile)

  




转载于:https://www.cnblogs.com/hongfuqitian/p/10141929.html

猜你喜欢

转载自blog.csdn.net/weixin_30617561/article/details/94878921