循环次数索引;枚举()

Index of number of loops; enumerate()

我刚刚完成我 python 书中的练习,我正在努力完成。

一开始,我应该列一个包含 10 个数字和 5 个字母的列表。随机select4个元素打印中奖信息

from random import choice, branding

numbers_and_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                   '1', '2', '3', '4', '5']

print("If you've got those 4 numbers or letters you've won!!!")
for i in range(1, 5):
    print(choice(numbers_and_letters))

然后我想做一个循环,看看赢得我刚刚创建的那种彩票有多难。我需要制作一个名为 my_ticket 的列表,然后编写一个循环,不断拉取数字直到中奖。打印一条消息,报告循环必须调整多少次才能给出中奖彩票。

from random import choice
from itertools import count

numbers_and_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                       '1', '2', '3', '4', '5']
winning_numbers = []
my_ticket = ['a','1', '5', 'j']

for i in count():   #infinite loop
    for i in range(1, 5):   # four elements from the numbers_and_letters list
        i = choice(numbers_and_letters)
        winning_numbers.append(i)
    print(winning_numbers)
    
    if sorted(winning_numbers) != sorted(my_ticket):
        winning_numbers.clear()
    elif sorted(winning_numbers) == sorted(my_ticket):
        print('The numbers are identical')
        break

我唯一需要做的就是计算代码通过循环集成了多少次。我知道我需要使用 enumerate(),但是,我不确定如何将它应用到我的代码中。

enumerate() 函数接受一个列表,并从列表中的所有元素生成元组,如 [(0, elem1), (1, elem2), ...]

所以你可以用它来计算循环有多少次 运行 像这样:

for index, i in enumerate(count()):   #infinite loop
    for i in range(1, 5):   # four elements from the numbers_and_letters list
        i = choice(numbers_and_letters)
        winning_numbers.append(i)
    print(winning_numbers)
    
    if sorted(winning_numbers) != sorted(my_ticket):
        winning_numbers.clear()
    elif sorted(winning_numbers) == sorted(my_ticket):
        print('The numbers are identical')
        print('It took %d runs!' % (index + 1))
        break

Index + 1 因为索引从 0 开始。

您可以使用临时计数器 cnt 来跟踪您的循环从列表中提取元素并将其与票匹配的次数 首先在循环外用0初始化它

然后在每次循环运行时递增 cnt,如果找到匹配 print(cnt) 然后再次将 cnt 设置为 0(在 if 内)以进行下一次迭代

无需使用枚举。 'Count' 没问题。

这里对代码稍作修改使其工作:

from random import choice
from itertools import count

numbers_and_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                       '1', '2', '3', '4', '5']
winning_numbers = []
my_ticket = ['a','1', '5', 'j']

def get_random_ticket():
    res = []
    for i in range(4):   # four elements from the numbers_and_letters list
        i = choice(numbers_and_letters)
        res.append(i)
    return res

winning_numbers = get_random_ticket()
print(winning_numbers)

for i in count():   #infinite loop
    if sorted(winning_numbers) == sorted(get_random_ticket()):
        print('The numbers are identical')
        print(i) 
        break

您已经在计算在 count() 上找到与循环匹配的迭代次数。但是您稍后会用其他值覆盖从该循环获得的值,因为您多次重复使用变量名称 i

尝试为这三行中的变量使用不同的名称,而不是重复使用 i:

for draw_count in count():
    for character_count in range(1, 5):
        character = choice(numbers_and_letters)

现在您以后可以使用 draw_count。您可能想要打印出 draw_count + 1,因为 itertools.count 迭代器默认从零开始。

要计算代码通过循环集成的次数,只需添加一个计数器即可。

from random import choice
from itertools import count

numbers_and_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                       '1', '2', '3', '4', '5']
winning_numbers = []
my_ticket = ['a','1', '5', 'j']

a = 0
for i in count():   #infinite loop
    for i in range(1, 5):   # four elements from the numbers_and_letters list
        i = choice(numbers_and_letters)
        winning_numbers.append(i)
    print(winning_numbers)
    a += 1
    if sorted(winning_numbers) != sorted(my_ticket):
        winning_numbers.clear()
    elif sorted(winning_numbers) == sorted(my_ticket):
        print('The numbers are identical')
        print(a)
        break    

这是输出(圆点表示打印了几个winning_numbers)-

......
......
......
......
['4', 'd', 'h', '3']
['h', 'd', 'h', 'j']
['5', 'd', '5', 'c']
['1', '5', 'j', 'a']
The numbers are identical
2852