简体   繁体   English

Python中的统计信息模式函数异常

[英]Statistics Mode function Exceptions in Python

I have compiled a small code using the mode function from the statistics library in python. 我已经使用python统计数据库中的mode函数编译了一个小代码。 The code is basically taking input from sensors, listing them in an array of 10 inputs and then finding the mode in that list. 该代码基本上是从传感器获取输入,将它们以10个输入的阵列列出,然后在该列表中找到模式。 The problem is that as soon as there are 2 equally common values, the codes gives "StatisticsError: no unique mode". 问题在于,只要有2个相同的通用值,代码就会给出“ StatisticsError:无唯一模式”。

Instead of giving an error, I want it to print the data with the lesser value. 我希望它不输出错误,而是以较小的值打印数据。 This might be possible if I could access the list which the mode function makes and then compare the "2 or more modes", but I don't quite know how to do that. 如果我可以访问模式函数创建的列表,然后比较“ 2个或更多模式”,则可能会这样做,但是我不太清楚该怎么做。

import RPi.GPIO as GPIO
import time
import math
import statistics
GPIO.setmode(GPIO.BCM)

TRIGA = 23 
ECHOA = 24
TRIGB = 17 
ECHOB = 27

dist_lista=[]
dist_listb=[]

print "Distance Measurement In Progress"

GPIO.setup(TRIGA,GPIO.OUT)
GPIO.setup(ECHOA,GPIO.IN)
GPIO.setup(TRIGB,GPIO.OUT)
GPIO.setup(ECHOB,GPIO.IN)

GPIO.output(TRIGA, False)
print "Waiting For Sensor To Settle"
time.sleep(1)
GPIO.output(TRIGB, False)
time.sleep(1)

def roundoff(x):
    return int(math.ceil(x/10.0))*10

def function(TRIG, ECHO, var):
    dist_list = []
    for i in range (0,10):
        GPIO.output(TRIG, True)
        time.sleep(0.00001)
        GPIO.output(TRIG, False)

        while GPIO.input(ECHO)==0:
            pulse_start = time.time()

        while GPIO.input(ECHO)==1:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17150
        distance = roundoff(distance)
        dist_list.append(distance)
        time.sleep(0.01)
    if(distance<350 and distance>40):
        try:
            print "Distance",var, ":", statistics.mode(dist_list),"cm"
        except statistics.StatisticsError as e:
            print "Error: ", e
    time.sleep(0.1)
while True:
    function(TRIGA, ECHOA, "A")
    function(TRIGB, ECHOB, "B")

GPIO.cleanup()

Thank you in advance 先感谢您

Use this function instead of statistics.mode : 使用此函数代替statistics.mode

def lower_mode(sequence):
    try:
        return statistics.mode(sequence)
    except statistics.StatisticsError as e:
        return sorted(sequence)[len(sequence)//2 - 1]

You can then replace the whole try-except block in your code with this call: 然后,您可以使用以下调用替换代码中的整个try-except块:

if(distance < 350 and distance > 40):
    print "Distance", var, ":", lower_mode(dist_list), "cm"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM