Python面试题
1、去除列表中的重复元素
#_*_coding:utf-8_*_ ls = [1,3,6,9,2,5,1,3,7,8,6] print('ls >>> ',ls) # 方法1 ls1 = list(set(ls)) print('ls1 >>> ',ls1) # 方法2 ls2 = {}.fromkeys(ls).keys() ls2 = [l for l in ls2] print('ls2 >>> ',ls2) # 方法3 ls3 = list(set(ls)) ls3.sort(key=ls.index) #保持原list元素顺序 print('ls3 >>> ',ls3) # 方法4 ls4 = [] [ls4.append(i) for i in ls if i not in ls4] print('ls4 >>> ',ls4)
2、删除指定文件
#_*_coding:utf-8_*_ import os filepath = '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)