我正在尝试创建一个程序,用户可以在其中输入多个彩票号码,并将这些号码与一组中奖号码进行比较。我知道我可以通过使用几个if语句来实现,但我认为必须有一种方法在循环中实现这一点。我尝试了一些使用“for key in_u__;”的循环,但我一直收到错误
amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
'1': '1',
'2': '2',
'3': '3',
'4': '4',
'5': '5',
'6': '6',
}
for i in range (0, amount, 1):
tickets[i] = {
'1': input('Input #1 '),
'2': input('Input #2 '),
'3': input('Input #3 '),
'4': input('Input #4 '),
'5': input('Input #5 '),
'6': input('Input Powerball '),
}
for i in range (0, len(tickets), 1):
ticketMatch[i] = 0
if tickets[i]['1'] in winingNumbers.values():
ticketMatch[i] += 1
if tickets[i]['2'] in winingNumbers.values():
ticketMatch[i] += 1
如有任何提示或提示,将不胜感激。谢谢
遍历任何字典都非常简单。假设我们有以下词典:
我们想打印出键及其值
然而,对于您试图实现的目标,可能根本不需要使用字典,就像@ggorlen评论的那样
我想出了一个快速的表演来做同样的事情
我不知道为什么你要把每张彩票的1号和2号与中奖总人数进行对比,因为这不是普通彩票的工作方式,这就是为什么我的版本看起来有点不同,但当然,如果这是你想要的,你可以很容易地进行更改
O(1)
)-迭代dict
的所有值与list
一样慢-但是创建字典比创建list
慢,占用更多的计算机内存李>set
操作可以避免使用if's
级联-有关示例,请参阅下文李>使用
split()
和列表分解*a,b=[1,2,3,4]
可以更快地在循环中输入:输出:
(尽管对于根本不输入NUMEBR或输入的NUMEBR太少/超出范围的用户,可能需要进行更多检查:Asking the user for input until they give a valid response)
对于乐透比较,可以使用
set
-操作快速检查带有一组()数字的“彩票”列表中的正确数字检查彩票列表将是
O(n)
(其中n
==彩票数量)-检查号码是否与中奖号码匹配是快速的:O(1)
并避免if ..:
您可以这样做(完全随机示例):
输出:
见:
相关问题 更多 >
编程相关推荐