如何找到数字范围

lsb*_*123 3 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)
Run Code Online (Sandbox Code Playgroud)

它不起作用

Ash*_*ary 6

您可以使用该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
Run Code Online (Sandbox Code Playgroud)

  • @StevenRumbalski修正了错字,我认为如果OP希望3.1落入3.1-3.3则可以使用bisect_right,如果3.1属于2.9-3.1则可以使用bisect_left. (2认同)

cht*_*mon 6

如何使用更多的numpy功能?

import numpy

numbers = numpy.loadtxt('test.txt')
bins = numpy.arange(2.5, 3.51, 0.2) #  3.5 won't work due to floating point issues
counts, _ = numpy.histogram(numbers, bins)
Run Code Online (Sandbox Code Playgroud)

如果您不想使用numpy,您可以通过直接计算数字对于相等大小的二进制文件的数据库来获益:

numbers = [float(n) for n in open('test.txt') if len(n.strip())]
start = 2.5
width = 0.2
end = 3.7

def position(n):
    return int((n - start)/width)

counts = [0 for i in range(position(end))]
for n in numbers:
    counts[position(n)] += 1
Run Code Online (Sandbox Code Playgroud)