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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值