创建Python列表
movies = [“The Holyy”, “the life”]
变量标识符没有类型
可以存储混合类型的数据
movies.insert(1,1975)
movies.append(1983) #end
for i in movies:
print i
- ’ ” are the same in python*
and if you want to use ” in a string, you can use : \”
多重列表
print(movies[4][1][3])
isinstance()
isinstance(movies,list)
True
def
def name(para):
ahead of where you use it
BIF: 内置函数
len()提供长度
list() create a null list
range() 返回一个迭代器,根据需要生成一个指定范围的数字。
enumerate() 创建成对数据的一个编号列表,从0开始。
int() 转换成一个整数(如果可行)
next() 返回一个可迭代的数据结构(如列表)中的下一项。
strip()可以从字符串中去除不想要的空白符
sys.stdout 是标准输出,从标准库的sys模块中访问
在IDLE shell中
使用 Alt + P 和N来切换
PyPI “pie-pie”
Python Package Index
可以通过这个分享
注意: 在每次更新API的时候,尽量使用可选参数:
def print_lol(the_list,level=0): #增加了一个缺省值使得“level”变成一个可选的参数
现在,函数支持不同的签名,并且功能可以照旧。
文件 & 应对错误机制
the_file = open(‘hello.txt’)
the_file.close()
data.seek(0) #回到文件的起始位置,对于Python的文件也可以使用“tell()”
import os
os.getcwd() # get current addr
os.chdir('../Thenewfiles')
PS:the_file = open(‘hello.txt’) 然后 做each for in the_file 就不用 each.readlilne()了
(A,B)=each_line.split(“:”) #在:这个两边分开 (这个貌似就是 必须要文本都有 : ,否则就会出问题, 但是在 help中可以找到注释,可以设置:的深度
另外,通过提前预判 也是可以的
if not each_line.find(‘:’) == -1:
另外,通过try/except也可以实现
try:
maybe something wrong
except:
your recovery code
最好的情况就是直接pass掉: except: pass
如果需要特定指定异常:
except ValueError:
pass
except IOError: print(‘the data file is missing’)
处理缺少的文件
如果数据文件缺少,这两个版本都会崩溃,产生一个 IOError并生成一个traceback
import os
if os.path.exists('hello.txt'):
data = open('hello.txt')
for...
data.close()
else:
print('The data file is missing')
#####文件写入
out = open ("data.out","w") #数据文件对象
print("Norwegian Blues stun easily.",file = out) #所写数据文件对象的名 #这个好像不对
out.write('dkkdkd')
out.close() #重要,一定要这样做,成为刷新输出(flushing)
PS:如果不要清除,追加信息 : w+
*发生异常之后文件会保持打开!*
所以需要用 finally 来扩展 try
try: except:IOError finally:man_file.close()
*使用with 处理文件
try:
data = open(‘its.txt’,’w’)
print (“It’s …”,file = data)
except IOError as err:
print(‘File error:’+str(err))
finally:
if ‘data’ in locals():
data.close()
```
try:
with open('its.txt',"w") as data:
print("It's...", file = data)
except IOError as err:
print('File error: ' +str(err))
这样就不用担心文件关闭的问题了:with使用了 上下文管理协议的 python技术。
*pickle
必须以二进制访问模式打开这些文件,dump() & load()
import pickle
with open('mydata.pickle','wb') as mysavedata: #wb告诉以二进制写入
pickle.dump([1,2,'three'],mysavedata)
with open('mydata.pickle','rb') as myrestoredata:
a_list = pickle.load(myrestoredata)
print(a_list)
如果出问题了,那么就会产生一个PickleError类型的异常
排序
有两种方式:
1.原地排序(In-place sorting): sort()
2.复制排序(Copied sorting): sorted()
data.sort()
= sorted(data)
串链
1.方法串链 data.strip().split(‘,’) 最好从左往右读
2.函数串链 需要从右往左读