Python面试常见题
1、Python生成随机数
import random
for i in range(100):
print(random.randint(0,100))
2、字符串逆序
a = "abcdefg"
print(a[::-1])
a = "abcdefg"
b = list(a)
b.reverse()
b = ''.join(b)
print(b)
3、判断一个字符串是否为回文字符串
(abcdcba 一个字符串从前往后读和从后往前读是一样的。)
a = "abcdcba"
if a == a[::-1]:
print('是回文函数')
4、随机生成100个数,然后写入文件
import random
with open('f.txt','wb') as f:
for i in range(100):
n = random.randint(1, 100)
f.write((str(n) + "\n").encode('UTF-8'))
5、给定字典进行排序
给定dict = {'a':3,'bc':5,'c':3,'asd':4,'33':56,'d':0}
dict = {'a':3,'bc':5,'c':3,'asd':4,'33':56,'d':0}
print(dict.items())
print(sorted(dict.items(),key = lambda i:i[0],reverse = True))
给定list2 = [[1,2],[4,6],[3,1]]
list2 = [[1,2],[4,6],[3,1]]
list2.sort(key = lambda x:x[0],reverse = False)
print (list2)
6、对列表进行去重
1.对 a = [1,3,2,2,1,5,5,3]
a = [1, 3, 2, 2, 1, 5, 5, 3]
print(set(a))
a = [1, 3, 2, 2, 1, 5, 5, 3]
for i in a:
if a.count(i) >1:
a.remove(i)
print(a)
7、去重字符串
s = 'abddaddfd'
print(''.join(set(list(s))))
8.有UTF-8编码的文件a.txt。文件路径在E盘根目录,写一段程序逐行读入文本文件。并在屏幕(gbk编码)打印出来
65001 utf-8 936 GBK 编码 采用chcp命令查看当前的CMD编码。
fp = open("f:\test\a.txt",'r')
content = fp.read()
fp.close()
print (content.decode("utf-8").encode("gbk","ignore"))

浙公网安备 33010602011771号