python-查找列表中特定范围的项目总数

标签 python

我在 Python 中有一个包含许多 float 的列表。我想知道任意两个整数之间有多少个 float 。最简单、最有效的方法是什么?

例子.py - 如何确定 int(1) 和 int(8) 之间有 3 个 float 。

between_List = [1, 1.2, 1.8, 1.45, 8]

最佳答案

您可以简单地求和一个元素在 3-4 范围内的次数:

l = [3.4,4.5,3.2,5.6]

print(sum(3 <= ele <= 4  for ele in l))
2

或者使用 numpy:

将 numpy 导入为 np

l = [3.4, 4.5, 3.2, 5.6]
arr = np.array(l)

print(((3 <= arr) & (arr <= 4)).sum())
2

如果你想检查你是否真的有一个 float 也使用 issinstance:

  print(sum(3 <= ele <= 4 and isinstance(ele,float) for ele in l))

如果你真的想计算两个实际整数之间的 float 总数:

l = [1.3, 3, 3.4, 34.5, 3.2, 4, 5.6]


def find_fs(l, i, j):
    try:
        start, end = l.index(i), l.index(j)
        return sum(isinstance(ele, float) for ele in islice(l, start + 1, end))
    except IndexError:
        return 0
print(find_fs(l,3, 4))
3

关于python-查找列表中特定范围的项目总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32018206/

相关文章:

python - 如何在python中将一个csv拆分为多个文件

Python3 从字典创建 3-D 图(值 : Tuple)

python - Pygame - 在 Sprite 中加载图像

python - 从字符串列中提取数字

python arma fitting 运行太慢?

python - 简单的 Yahtzee 模拟没有给出正确的结果?

python - 验证准确性没有提高

python - psycopg2 关闭连接池

python - 在 python 脚本中使用 "pip install/uninstall"

python - 地理坐标值错误 : undefined inverse geodesic