Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

for loop - 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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...