如何在Python中重复一个函数(完整的初学者-有史以来的第一行代码) [英] How to repeat a function in Python (complete beginner - first lines of code ever)
问题描述
我必须构建以下代码(即,不能用其他方式编写).我知道还有其他更好的方法可以达到最终结果,但是我想使用此代码,然后重复此操作以列出清单.
I have the following code which I have to build upon (i.e. it can't be written a different way). I know there are other better ways of achieving the end result, but I want to use this code and then repeat it to make a list.
from random import choice
number_list = range(1,1001) # Creates a list from 1 to 1000
random_from_list = choice(number_list) # Chooses a random number from the list
我现在要在100次以上重复选择功能,然后打印从1000个数字列表中选择的100个随机数字列表.我已经阅读了"for"循环,但是在这里看不到如何应用.
I want to now repeat the choice function above 100 times, then print that list of 100 random numbers that I have chosen from my list of 1000 numbers. I have read up on "for" loops but I can't see how to apply it here.
推荐答案
如果您不需要建立列表,则可以一次打印一个列表:
If you don't need to build up your list you could just print them one at a time:
for _ in range(100):
print(choice(number_list))
如果您想先构建列表,则可以使用列表理解":
If you want to build your list first you can use a "list comprehension":
choices = [choice(number_list) for _ in range(100)]
print(choices)
这篇关于如何在Python中重复一个函数(完整的初学者-有史以来的第一行代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!