简体   繁体   English

循环数索引; 枚举()

[英]Index of number of loops; enumerate()

I'm just going through the exercise in my python book and I'm struggling with the finish.我只是在完成我的 python 书中的练习,我正在努力完成。

In the beginning, I was supposed to make a list with a series of 10 numbers and five letters.一开始,我应该列出一个由 10 个数字和 5 个字母组成的列表。 Randomly select 4 elements and print the message about the winning ticket.随机 select 4 个元素,打印中奖信息。

 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))

Then I suppose to make a loop to see how hard it might be to win the kind of lottery I just created.然后我想做一个循环来看看赢得我刚刚创建的那种彩票有多难。 I need to make a list called my_ticket then write a loop that keeps pulling numbers until the ticket wins.我需要创建一个名为 my_ticket 的列表,然后编写一个循环,不断拉数字,直到票中奖。 Print a message reporting how many times the loop had to tun to give a winning 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

The only thing I need to do is to count how many times the code integrated through the loop.我唯一需要做的就是计算代码通过循环集成了多少次。 I know I need to use enumerate(), however, I'm not sure how to apply it to my code.我知道我需要使用 enumerate(),但是,我不确定如何将它应用到我的代码中。

The enumerate() function takes a list and makes tuples from all of the elements in the list like [(0, elem1), (1, elem2), ...] . enumerate() function 获取一个列表,并从列表中的所有元素中生成元组,例如[(0, elem1), (1, elem2), ...]

So you can use it to count how many times the loop has run like this:因此,您可以使用它来计算循环运行的次数,如下所示:

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 because the indices start with 0.索引 + 1,因为索引从 0 开始。

You can use a temproary counter cnt to keep track on how many times your loop pulls the elements from the list and match it with the ticket First initialise it with 0 outside the loop您可以使用临时计数器cnt来跟踪循环从列表中提取元素的次数并将其与票证匹配 首先在循环外使用 0 对其进行初始化

Then increment cnt each time your loop runs, if a match is found print(cnt) and then afterwards again set cnt to 0(inside if) for next iteration然后每次循环运行时递增cnt ,如果找到匹配print(cnt)然后再次将 cnt 设置为 0(inside if) 以进行下一次迭代

No need to use enumerate.无需使用枚举。 'Count' is fine. “计数”很好。

Here's a slight modification to the code that makes it work:下面是对使其工作的代码的轻微修改:

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

You are already counting the number of iterations it takes you to find a match with your loop on count() .您已经在计算在count()上找到与循环匹配所需的迭代次数。 But you're overwriting the value you get from that loop with other values later on, since you are reusing the variable name i several times.但是您稍后会用其他值覆盖从该循环中获得的值,因为您多次重复使用变量名i

Try using different names for the variables in these three lines, rather than reusing i :尝试为这三行中的变量使用不同的名称,而不是重用i

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

Now you can use draw_count later on.现在您可以稍后使用draw_count You probably want to print out draw_count + 1 , since the itertools.count iterator starts at zero by default.您可能想要打印出draw_count + 1 ,因为itertools.count迭代器默认从零开始。

To count the number of times the code integrated through the loop, just add a counter.要计算代码通过循环集成的次数,只需添加一个计数器。

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    

This is the output (dots indicate there are several printed winning_numbers)-这是 output(点表示有几个打印的winning_numbers)-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM