我在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