[英]Why does the For loop produce variable list length
I need the following code when executed to produce a list with a fixed length of 4 elements.执行时我需要以下代码来生成一个固定长度为 4 个元素的列表。 Why doesn't it work with the for loop?
为什么它不适用于 for 循环?
from random import choice
pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = []
for pulled_ticket in range(4):
pulled_ticket = choice(pool)
if pulled_ticket not in winning_ticket:
winning_ticket.append(pulled_ticket)
print(winning_ticket)
When I execute the code, the results look something like this:当我执行代码时,结果如下所示:
[7, 4, 8, 'e']
[5, 'e']
['e', 6, 3]
But with the while loop, I don't have this problem:但是使用 while 循环,我没有这个问题:
from random import choice
pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = []
while len(winning_ticket) < 4:
pulled_ticket = choice(pool)
if pulled_ticket not in winning_ticket:
winning_ticket.append(pulled_ticket)
print(winning_ticket)
The list length is always four:列表长度始终为四:
['e', 5, 1, 8]
[7, 'd', 2, 8]
[2, 6, 'e', 10]
Thanks a lot!非常感谢!
The answer it pretty logical when using for pulled_ticket in range(4):
you are going to trigger the choice
and then if
4 times, if you pick the same number twice it will not be added and you will finish with 3 items in the list使用
for pulled_ticket in range(4):
您将触发choice
,然后if
选择4次,如果您两次选择相同的数字,则不会添加,您将完成列表中的3 个项目
the while loop
waits for there to be 4 items so if it gets the same choice multiple times it will just continue while loop
等待有 4 个项目,所以如果它多次获得相同的选择,它将继续
Main issue is like I stated in the comments, Your for loop only always does 4 iterations.主要问题就像我在评论中所说的那样,你的 for 循环只总是进行 4 次迭代。 While your while loop goes on till the reached length is 4.
当您的 while 循环继续进行直到达到的长度为 4 时。
Example output:示例 output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
[4, 8, 'a']
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
[9, 6, 'a', 'b']
You can see that the for loop gives you a 3 size list while doing 4 passes, meaning once it hit the same random number.您可以看到 for 循环在进行 4 次传递时为您提供了一个 3 大小的列表,这意味着一旦它命中相同的随机数。 A way easier way to do this could be so simply use choices, Like @norie, bc you can specify the size of the returning list and there is no need for loops.
一种更简单的方法是简单地使用选择,就像@norie,因为你可以指定返回列表的大小并且不需要循环。
print(choices(pool, k=4))
['a', 8, 'd', 8]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.