社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

nick_14159

nick_14159 最近创建的主题
nick_14159 最近回复了
8 年前
回复了 nick_14159 创建的主题 » 在python中计算列表中介于一个范围之间的浮动数

这会让你开始。这是另一个列表理解检查坐标对列表,看看每个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