这会让你开始。这是另一个列表理解检查坐标对列表,看看每个x和y是否在间隔(0,1)内。
from random import random
print(len([(x,y) for x,y in [(2*random(),2*random()) for _ in range(1500)] if 0 < x < 1 and 0 < y < 1]))
如果您的唯一目标是计算所有对,使x、y对处于间隔(0,1)内,那么while循环将通过避免创建列表而更有效。
def rand_coordinates(num_of_pairs):
"""Counts the number of randomly generated x,y
pairs in the range of [0,2) where x and y are
contained in the interval from (0,1)"""
count = 0
while num_of_pairs:
x,y = 2*random(),2*random()
if 0 < x < 1 and 0 < y < 1:
count += 1
num_of_pairs -= 1
return count