2021-03-15锦学长之50题

2021-03-15  本文已影响0人  Cipolee

NO.53集合

关于集合的处理,一般都是先按照list做,做完之后再使用set转换

import random
def create_set():
    list_=[]
    i=random.randint(0,10)
    for _ in  range(i):
        list_.append(random.randint(0,1001))
    return set(list_)
A=create_set()
B=create_set()
def judge(a,b):
    list_1=[int(i) for i in input().split()]
    list_2=[int(i) for i in input().split()]
    if list_1.sort()==a.sort() and list_2.sort==b.sort():
        return True
    else:
        return False
flag=False
for i in range(3):
    if judge(list(A|B),list(A&B)):
        print("结果正确")
        flag=True
        break
    else:
        print("输入错误请重新属于一组值")
    #print(judge())
if not flag:
    print("三次机会已经用完,公布正确结果")
    print(A|B)
    print(A&B)

NO.53读写文件

在使用open时,一般要指定读或写的操作

r 读 w 写 r+即读又写开头 w+即写又读

open不close则不能写进去数据

f1=open(r'C:\AppData\imagines\new.txt','w')
f2=open(r'C:\AppData\imagines\copy.txt','r')
f1.write(f2.read())
f1.close()
f2.close()

NO.54 排序后,换行写入

f1=open(r'C:\AppData\imagines\numbers.txt','r')
line=f1.readline()
ans=[]
while line:
    ans.append(float(line))
    line=f1.readline()
f1.close()
f2=open(r'C:\AppData\imagines\Sort.txt','w+')
for j in sorted(ans):
    f2.write("{}\n".format(str(j)))
f2.close()

均值可以使用mean方法求得,var可以求方差

f1=open(r'C:\AppData\imagines\numbers.txt','r')
line=f1.readline()
ans=[]
while line:
    ans.append(float(line))
    line=f1.readline()
f1.close()
f2=open(r'C:\AppData\imagines\Sort.txt','w+')
f2.write("{}\n".format(str(np.mean(ans))))
f2.write("{}\n".format(str(np.var(ans))))
f2.close()

NO.56 只有字符串可以相加,故路径名中数字要转化为字符串

\f时转义字符,应该在字符串前标注r''这样转义字符就不会被翻译

多文本输入要点,每个文本都在循环中打开关闭,并写入‘\n’以换行

写入的文本只有在操作完成后进行关闭操作

a='C:\AppData\imagines\\folder\\file'
txt_list=[]
for i in range(1,5):
    txt_list.append(a+str(i)+'.txt')
f2=open(r'C:\AppData\imagines\\folder\merge.txt','w+')
for i in range(4):
    f1=open(txt_list[i],'r')
    f2.write(f1.read())
    f2.write('\n')
    f1.close()
f2.close()

NO.57 f.read()只能使用一次,再下面就只能read空了

in_factor=['A','e','i','o','u','E','I','O','U','a']
txt_list=[]
f2=open(r'C:\AppData\imagines\word.txt','r')
for i in f2.read().split():
    if i[0] in in_factor:
        txt_list.append(i)
f2.close()
f=open(r'C:\AppData\imagines\new_word.txt','w+')
for i in txt_list:
    f.write("{}\n".format(i))
f.close()

NO.58排序类题

name_list=[]
f=open(r'C:\AppData\imagines\names.txt','r')
for i in f.read().split():
    name_list.append(i)
name_list.append(input("请输入一个名字"))
name_list = sorted(name_list)
f.close()
f=open(r'C:\AppData\imagines\names.txt','w+')
for i in name_list:
    f.write("{}\n".format(i))
f.close()
上一篇下一篇

猜你喜欢

热点阅读