# 答案
def cards():
num = []
for i in range(2,11):
num.append(i)
num.extend(['J','Q','K','A'])
type = ['红心','草花','方块','黑桃']
result = []
for i in num:
for j in type:
result.append((j,i))
return result
print(cards())
写函数,传入n个数,返回字典{‘max’:最大值,’min’:最小值}
例如:min_max(2,5,7,8,4)
返回:{‘max’:8,’min’:2}
# 答案
def max_min(*args):
the_max = args[0]
the_min = args[0]
for i in args:
if i > the_max:
the_max = i
if i < the_min:
the_min = i
return {'max': the_max, 'min': the_min}
print(max_min(2, 4, 6, 48, -16, 999, 486, ))
map()函数
map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把
函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。
注意:map()函数在不改变原有的lisy,而是返回一个新的list
代码:
name=['alex','wupeiqi','yuanhao','nezha']
def sb(x):
return x+'_sb'
res = map(sb,name)
print(list(res))
用filter函数处理数字列表,将列表中所有的偶数筛选出来
num = [1,3,5,6,7,8]
num = [1,3,5,6,7,8]
def func(x):
if x%2 == 0:
return True
ret = filter(func,num)
print(list(ret))
f = filter(lambda d:d['price']>=100,portfolio)
print(list(f))
1、请分别介绍文件操作中不同的打开方式之间的区别:
模式
含义
r
文本只读模式
rb
二进制模式 这种方法是用来传输或存储,不给人看的
r+
读写模式,只要有r,那么文件必须存在
rb+
二进制读写模式
w
只写模式,不能读,用w模式打开一个已经存在的文件,如果有内容会清空,重新写
wb
以二进制方式打开,只能写文件,如果不存在,则创建
w+
读写模式,先读后写,只要有w,会清空原来的文件内容
wb+
二进制写读模式
a
追加模式,也能写,在文件的末尾添加内容
ab
二进制追加模式
a+
追加模式,如果文件不存在,则创建文件,如果存在,则在末尾追加
ab+
追读写二进制模式,从文件顶部读取文件,从文件底部添加内容,不存在则创建
2、有列表 li = ['alex', 'egon', 'smith', 'pizza', 'alen'], 请将以字母“a”开头的元素的首字母改为大写字母;
# 答案
li = ['alex', 'egon', 'smith', 'pizza', 'alen']
li_new = []
for i in li:
if i.startswith('a'):
li_new.append(i.capitalize())
else:
li_new.append(i)
print(li_new)
for i in range(len(li)):
if li[i][0] == 'a':
li[i] = li[i].capitalize()
else:
continue
print(li)
3、有如下程序, 请给出两次调用show_num函数的执行结果,并说明为什么:
num = 20
def show_num(x=num):
print(x)
show_num()
num = 30
show_num()
# 答案
方法一:
import os
p = 'poetry.txt'
file = open(p,'r',encoding='utf-8')
print(file)
pnew = '%s.new'%p
filenew = open(pnew,'w',encoding='utf-8')
str1 = '晴川历历汉阳树,芳草萋萋鹦鹉洲。'
for i in file:
if str1 in i:
i = ''
filenew.write(i)
else:
filenew.write(i)
file.close()
filenew.close()
os.replace(pnew,p)
方法二:逐行读取文件
import os
f1=open('poetry.txt', 'r',encoding='utf-8')
str='晴川历历汉阳树,芳草萋萋鹦鹉洲。'
with open('poetry1.txt', 'w', encoding='utf-8') as f2:
ff1='poetry.txt'
ff2='poetry1.txt'
for line in f1:
if str in line:
line=''
f2.write(line)
else:
f2.write(line)
f1.close()
f2.close()
os.replace(ff2,ff1)
# 答案
with open('username.txt','r+',encoding='utf-8') as f:
str1 = 'alexx'
i = f.read()
print(i)
if str1 in i:
print("the user already exist in")
else:
f.write('\nalexx')
# 答案
import os
a = 'user_info.txt'
b = 'user_info1.txt'
with open(a,'r',encoding='utf-8') as f:
with open(b, 'w', encoding='utf-8') as f2:
for i in f:
if '100003' in i:
pass
else:
f2.write(i)
os.replace(b,a)
# 答案
file = 'user_info.txt'
old_str = '100002'
new_str = 'alex, 100002'
file_data=''
with open(file,'r',encoding='utf-8') as f1:
for line in f1:
if old_str in line:
line =new_str
file_data +=line
with open(file,'w',encoding='utf-8') as f1:
f1.write(file_data)