python - 计算python中范围内列表中的 float 数量

标签 python python-3.x

我已经被这个任务困住了一段时间了。我已经使用下面的代码成功生成了 1500 个坐标,这些坐标为我提供了 0 到 2 (x,y) 之间的浮点值。

coordinates = [(random.random()*2.0, random.random()*2.0) for _ in range(15000)]
print(coordinates)

但是现在我需要创建一个计数器来计算 0 到 1 之间的 float 并将其输出给用户。我尝试过使用 If 语句和 while 循环。我也在互联网上进行了窥探,但找不到任何有用的东西。有谁知道如何解决这个问题吗?

亲切的问候。

最佳答案

您可以使用简单的条件sum()如果 x 或/和 y 小于 1,则对元组求和 1:

import random

# your code used 15k tuples, your text says 1.5k - adapt the number to your liking
coordinates = [(random.random()*2.0, random.random()*2.0) for _ in range(1500)]

one_lower_1  = sum(1 for x,y in coordinates if x < 1 or  y < 1)
both_lower_1 = sum(1 for x,y in coordinates if x < 1 and y < 1)
x_lower_1    = sum(1 for x,_ in coordinates if x < 1)
y_lower_1    = sum(1 for _,y in coordinates if y < 1)

print(one_lower_1)
print(both_lower_1)
print(x_lower_1)
print(y_lower_1)

输出

1134
383
745
772

这本质上是一个生成器表达式,它仅从生成的坐标中过滤掉那些与if ....之后的部分匹配的对


我选择 sum(1 ... ) 方法,因为这样您就不必创建一个列表来获取其 len() ...如果您只需要元素计数然后生成所有元素,则对内存更友好。


来自 jpp's 的替代方式评论:

sum(x < 1 or  y < 1 for x,y in coordinates)

这是有效的,因为超过 10 True 的总和给出 10 - 每个 True counting as 1 :

print(sum(True for _ in range(10))) # 10

关于python - 计算python中范围内列表中的 float 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354679/

相关文章:

python - GAE 列出以名称开头的任务?

c++ - 嵌入式 Python 无法使用 NumPy 指向 Python35.zip - 如何修复?

python - 如何重启 PyQt5 应用程序

c++ - python中char *的问题

python - TensorBoard 元数据 UnicodeDecodeError

python - 调试 LDAP 库/连接 Wireshark/或其他

python - Json 转储字节在 Python 3 中失败

python - 删除这些元组列表中重复的列表组合的元组

python - 这里出了什么问题?意外引用现有实例而不是创建新实例

python - 在 Python 中找出代理类型(http,socks 4/5)?