Python遍历多个字典及其键

2024-09-19 23:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个程序,用户可以在其中输入多个彩票号码,并将这些号码与一组中奖号码进行比较。我知道我可以通过使用几个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

如有任何提示或提示,将不胜感激。谢谢


Tags: 用户in程序forinputifrangeamount
3条回答

遍历任何字典都非常简单。假设我们有以下词典:

d = {
    "a": 1,
    "z": 26
}

我们想打印出键及其值

for key in d: # note, key represents "a" and "z"
    print(key, d[key])

然而,对于您试图实现的目标,可能根本不需要使用字典,就像@ggorlen评论的那样

我想出了一个快速的表演来做同样的事情

query = "enter a lottery number or 'quit' to quit: "
entries = input(query)
numbers = []
while entries != "quit":
    numbers.append(entries)
    entries = input(query)

winning_numbers = "123456"

for i in range(len(numbers)):
    if numbers[i] == winning_numbers:
        print(f"ticket {i} is a winner!")

我不知道为什么你要把每张彩票的1号和2号与中奖总人数进行对比,因为这不是普通彩票的工作方式,这就是为什么我的版本看起来有点不同,但当然,如果这是你想要的,你可以很容易地进行更改

  • 只有当您有一个键并通过它存储一个值时,字典才有意义。访问键的值并检查键是否是字典的一部分是快速的(O(1))-迭代dict的所有值与list一样慢-但是创建字典比创建list慢,占用更多的计算机内存
  • 使用set操作可以避免使用if's级联-有关示例,请参阅下文

使用split()和列表分解*a,b=[1,2,3,4]可以更快地在循环中输入:

for _ in range(int(input("How many tickets do you want to enter? "))):
    *nums, power = map(int, 
         input( ("Input space seperated numbers of your ticket,"
                 " last one is Powerball: ") ).strip().split())
    print(nums, power)    

输出:

How many tickets do you want to enter? 3
Input space seperated numbers of your ticket, last one is Powerball: 1 2 3 4 99
    [1, 2, 3, 4] 99
Input space seperated numbers of your ticket, last one is Powerball: 2 3 4 7 199
    [2, 3, 4, 7] 199
Input space seperated numbers of your ticket, last one is Powerball: 4 2 4 5 6
    [4, 2, 4, 5] 6

(尽管对于根本不输入NUMEBR或输入的NUMEBR太少/超出范围的用户,可能需要进行更多检查:Asking the user for input until they give a valid response


对于乐透比较,可以使用set-操作快速检查带有一组()数字的“彩票”列表中的正确数字

检查彩票列表将是O(n)(其中n==彩票数量)-检查号码是否与中奖号码匹配是快速的:O(1)并避免if ..:

您可以这样做(完全随机示例):

import random 

def random_nums():
    """Returns a tuple of a frozenset of 5 numbers in the range [1..69]
    and one number in the range of [1..26] (aka: USA Powerball Lottery)"""
    return ( frozenset(random.sample(range(1,70), 5)), random.choice(range(1,27)) )

# draw the win-numbers
winning_nums = set(random.sample(range(1,70), 5))
powerball = random.choice(range(1,27))
# print them
print("Winner: ", *winning_nums, "   Powerball: ", powerball)


# generate random tickets
tickets = [ random_nums() for _ in range(10) ]

# check if ticket got something in common with winner numbers
for (nums, power) in tickets: 
    # fast set operations
    intersect = sorted(nums.intersection(winning_nums))
    wrong = sorted(nums.difference(winning_nums))
    p = 'correct' if power == powerball else 'wrong'
    n = "'nothing'"
    # some output
    print( ( f"You got {intersect or n} correct and guessed "
             f"{wrong or n} wrong. Powerball: {p}.") )

输出:

Winner:  14 49 26 27 60    Powerball:  6

You got [49] correct and guessed [21, 41, 59, 66] wrong. Powerball: wrong.
You got [60] correct and guessed [17, 19, 63, 68] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [10, 21, 51, 67, 69] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [18, 30, 40, 45, 52] wrong. Powerball: wrong.
You got [26, 27] correct and guessed [11, 37, 58] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [28, 33, 38, 59, 65] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [11, 18, 35, 61, 64] wrong. Powerball: wrong.
You got 'nothing' correct and guessed [2, 3, 47, 54, 63] wrong. Powerball: wrong.
You got [14] correct and guessed [23, 25, 58, 66] wrong. Powerball: wrong.
You got [27] correct and guessed [47, 52, 56, 58] wrong. Powerball: correct.

见:

amount = int(input('How many sets of numbers do you have?'))
winingNumbers = {1, 2, 3, 4, 5, 6}
tickets = [set() for _ in range(amount)]
ticketMatch = []


for i in range(amount):
    for j in range(6):
        if j == 5:
            tickets[i].add(int(input("Input Powerball ")))
        else:
            tickets[i].add(int(input("Input #" + str(j + 1) + " ")))

for i in range(amount):
    ticketMatch.append(len(tickets[i] & winingNumbers))

相关问题 更多 >