python - 如何找到数字范围

标签 python

我在 text.txt 文件中有一个数字列表。
2.50
2.56
2.81
2.86
2.84
3.21
3.47
2.91
2.96
3.11
2.83
2.89
2.94
2.94
3.34
3.44
2.94
2.96
3.04
3.01
2.85
3.05
3.10

我想对范围集中的每个数字进行分类。比如一个范围内有多少。
2.5-2.7
2.7-2.9
2.9-3.1
3.1-3.3
3.3-3.5

我试过了。

from __future__ import division
from math import *
from numpy import *
from string import*

infile = open('text1.txt', 'r')
text = infile.read().split('\n')
infile.close()
text.remove('')

numbers = []
for i in text:
count = 0
if (numbers[i] > 2.49) and (numbers[i] < 2.59):
    count += 1
    print("Number of elements", count)

它不工作

最佳答案

您可以使用 bisect 模块:

>>> import bisect
>>> ranges = [2.5, 2.7, 2.9, 3.1, 3.3, 3.5]
>>> nums = [2.5, 2.56, 2.81, 2.86, 2.84, 3.21, 3.47, 2.91, 2.96, 3.11, 2.83, 2.89, 2.94, 2.94, 3.34, 3.44, 2.94, 2.96, 3.04, 3.01, 2.85, 3.05, 3.1]
>>> lis = [0]*len(ranges)
for item in nums:
    ind = bisect.bisect(ranges, item) - 1
   lis[ind] += 1
for x, y in zip(zip(ranges, ranges[1:]), lis):
   print x, y
...     
(2.5, 2.7) 2
(2.7, 2.9) 6
(2.9, 3.1) 9
(3.1, 3.3) 3
(3.3, 3.5) 3

关于python - 如何找到数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18628838/

相关文章:

python - 如何使用理解按升序连续打印元组 (1,2,3),(2,3,4).....(10,11,12)

python - 显示 python 文件中使用的文件导入/使用情况

python RawConfigParser

python - 从 django 迁移开始

python - reshape LSTM 的 Keras 输入

python - 从列中过滤掉非数字值

python - 用于根据提交的字符串推断国家/地区的库或 API?

python - Django 与 SQL Server 上的数据库

python - 使用 Python 控制浏览器?

python - 将字符串转换为嵌套元组 : Python