本文主要是介绍python | Incorrect lottery numbers 存储格式正确的彩票号码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Incorrect lottery numbers 存储格式正确的彩票号码
The file lottery_numbers.csv
containts winning lottery numbers in the following format:
文件内容如下:
Sample data
week 1;5,7,11,13,23,24,30
week 2;9,13,14,24,34,35,37
…etc…
每一行都以周数开头,以1-39的7个数字结尾。
但是现在文件发生了一些乱码现象,具体出现的error如下:
Please write a function named filter_incorrect()
, which creates a file called correct_numbers.csv
.
这是我自己写的代码:
def filter_incorrect():open("correct_numbers.csv", 'w').close()# 保证了文件内容不会被重复写入。with open("lottery_numbers.csv") as original_file: # 开始读彩票文件for line in original_file:line1 = line.strip()line2 = line1.replace(";", ',')l_content = line2.split(",") # 获得数组,内容是每周所有单独的元素l_number = l_content[1:] # 数组,内容是每周彩票号码l_week = l_content[0].split() # 数组,[0]是week,[1]第x周if len(l_number) == 7:if l_week[1].isdigit():test = []# test用来保证该周的所有彩票号都符合要求for num in l_number:if num.isdigit() and 1 <= int(num) <= 39:test.append("True")else:test.append("False")if "False" not in test:with open("correct_numbers.csv", 'a') as correct_file:correct_file.write(line)# 确保号码、周数全部正确以后,写入if __name__ == "__main__":filter_incorrect()
刚刚回溯的时候发现没有写确保不重复的函数,但是误打误撞的居然对了,巧合巧合。另外,这一章内容主要是讲try-catch,但是我初学,完全没办法灵活运用,只好用if-else解决所有问题了。
接下来让我们看看标准答案。
def filter_incorrect():with open("lottery_numbers.csv") as input_file, open("correct_numbers.csv", "w") as result_file: # 一次性都打开了,方便呐!for row in input_file:parts = row.strip().split(";") # 原来还可以叠加使用!if len(parts) != 2: continueweek = parts[0].split(" ")error = False# 初始化error,error用来判断内容是否出错。if len(week) != 2 or week[0] != "week":error = Truetry:mika = int(week[1])except:error = True# 标答用了try, 我用的是if + .isdigit(). 用try是因为如果week[1]不是数字的话,会报错。再用except继续进行。但是让error变成了True.number_list = parts[1].split(",")if len(number_list) != 7:error = True# 这里不用try的原因是,即使数组长度不等于7,程序本身也不会报错。# numbers already listed --> to find out duplicateslisted = []for item in number_list:try:number = int(item)if number < 1 or number > 39 or number in listed:error = Truelisted.append(number)# number在范围以内,以及不重复的话,就加入到listed数组。except:error = Trueif not error: # not True是false,无法写入。error为False时写入。result_file.write(row)
总结(可能不对):
- 只有像判断内容是不是整数类型时,可能会报错,此时用
try-except
。比如number = int(item)
,但是像判断长度和数值范围这种并不报错的内容的话,直接使用if-else
。 - 辅助argument:error.
except
里面不能直接pass,否则函数直接停止运行,无法进行for循环。
题源:Helsinki, part 6
这篇关于python | Incorrect lottery numbers 存储格式正确的彩票号码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!