1、去除列表中的重复元素
#_*_coding:utf-8_*_ls = [1,3,6,9,2,5,1,3,7,8,6]print('ls >>> ',ls)# 方法1ls1 = list(set(ls))print('ls1 >>> ',ls1)# 方法2ls2 = {}.fromkeys(ls).keys()ls2 = [l for l in ls2]print('ls2 >>> ',ls2)# 方法3ls3 = list(set(ls))ls3.sort(key=ls.index) #保持原list元素顺序print('ls3 >>> ',ls3)# 方法4ls4 = [][ls4.append(i) for i in ls if i not in ls4]print('ls4 >>> ',ls4)
2、删除指定文件
#_*_coding:utf-8_*_import osfilepath = 't.txt'os.remove(filepath)
3、读取文件中的内容并打印在屏幕上
with open('1.txt','r') as fp: contents = fp.readlines() print(contents) for content in contents: print(content.replace('\n',''))
5、反向获取list元素最快的方式
ls = [1,3,6,9,2,5,1,3,7,8,6]ls6 = ls[::-1]
4、 list和tuple的互相转换
ts = (1, 3, 6, 9, 2, 5, 1, 3, 7, 8, 6)ls = [1, 3, 6, 9, 2, 5, 1, 3, 7, 8, 6]list(ts)tuple(ls)