python数字列表中某个数所占百分比_在Python中,如何检查列表中的2个数字是否在彼此的特定百分比内?...

我有一个很大的数字列表,我想知道它们中的任何一个是否大致相等.如果两个数字“近似相等”(为了我的目的),它们都落在彼此的10%之内(参见下面的两个例子.)然后我想将它们分成大约相等数字的单独列表.

示例#1

比较5.0和5.5:

5.5 / – 10%= 4.95到6.05(5.0在此范围内)

5.0 / – 10%= 4.50到5.50(并且5.5在此范围内)

因此,5.0和5.5大致相等.

例#2

比较5.0和5.6:

5.6 / – 10%= 5.04到6.16(5.0在此范围内)

5.0 / – 10%= 4.50到5.50(5.6不在此范围内)

因此,5.0和5.6并不大致相等.

我需要做的总结:

输入= {4.0,4.1,4.2,4.0,9.0,9.4,8.9,4.3}

期望输出= {4.0,4.1,4.2,4.0,4.3}和{9.0,9.4,8.9}

最佳答案

input_list = [4.0, 4.1, 4.2, 4.0, 9.0, 9.4, 8.9, 4.3]

results = {input_list[0]: [input_list[0]]} # Start with first value

for value in input_list[1:]: # loop through our entire list after first value

hi = value * 1.1

low = value * 0.9

print("Value: {0}\tHi: {1}\tLow:{2}".format(value, hi, low))

for existing in results: # search through our result set

found_similar = False

if low < existing < hi: # if we find a match

results[existing].append(value) # we add our value to the list for that set

found_similar = True

break

if not found_similar: # if we looped through our entire results without a match

results[value] = [value] # Create a new entry in our results dictionary

for entry in results:

print(results[entry])

会给:

results = { 9.0: [9.0, 9.4, 8.9],

4.0: [4.0, 4.1, 4.2, 4.0, 4.3] }

此代码以列表中的第一个值开头,并查找在该列表的10%范围内的所有后续值.因此,在您的示例中,它以4开头,并查找所有类似的值.任何不在10%以内的值都会添加到新的“集合”中.

因此,一旦达到9.0,它就会发现它不匹配,因此它将新的结果集添加到结果字典中,其键为9.0.现在当它考虑9.4时,它在4.0列表中找不到匹配,但它确实在9.0列表中找到匹配.因此它将此值添加到第二个结果集.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值