简体   繁体   English

如何在Python中计算位数的平均值

[英]How to calculate the average of digit in Python

I have a assignment for my computer class, and the one of the question asked us to write a code which will calculate the average of the digits until it gets to a letter (alphabet). 我为我的计算机课分配了一个作业,其中一个问题要求我们编写一个代码,该代码将计算数字的平均值,直到达到字母(字母)为止。

This was the description: 描述如下:

This function receives as input one string containing digits or letters. 该函数接收一个包含数字或字母的字符串作为输入。 The function should return one float number contaning the average calculated considering all the digits in the string starting from the first position in the string and considering all digits until one letter is found or until reaching the end of the string. 函数应返回一个浮点数,该浮点数应包含从字符串的第一个位置开始考虑字符串中的所有数字并考虑所有数字直到找到一个字母或直到到达字符串末尾的平均值。 If there are no digits the function should return the value 0.0 . 如果没有数字,该函数应返回值0.0

So I came up with the following code: 所以我想出了以下代码:

def avgUntilLetter (st):
    digits1 = [int(x) for x in st if x.isdigit()]
    total = sum(digits1)
    if digits1:
        avg = float(total) / len(digits1)
        return avg
    if st.isalpha():
        return 0.0

For answer, for example, I should get 2.0 as return value if the CodeWrite put in avgUntilLetter('123a456') . 例如,对于答案,如果CodeWrite放入avgUntilLetter('123a456') ,则我应该获得2.0作为返回值。 I'm getting the average of all digits, what do I need to put in to my code to fix this? 我正在获得所有数字的平均值,我需要在代码中添加什么才能解决此问题?

You are taking all digits, not just the ones at the start. 您正在使用所有数字,而不仅仅是开头的数字。 You need to stop calculating when you encounter the first non-digit. 遇到第一个非数字时,您需要停止计算。

This is easiest if you just loop over all characters one by one and break out when you reach the first non-digit: 如果仅一个接一个地循环所有字符并在到达第一个非数字时中断,这是最简单的:

def avgUntilLetter(st):
    total = count = 0
    for x in st:
        if not x.isdigit():
            break
        count += 1
        total += int(x)
    if not count:
        return 0.0
    return float(total) / count

Here count tracks how many digits we found at the start; 这里count跟踪我们在一开始发现的位数; if it is still 0 no digits were found. 如果仍然为0找不到数字。

Demo: 演示:

>>> def avgUntilLetter(st):
...     total = count = 0
...     for x in st:
...         if not x.isdigit():
...             break
...         count += 1
...         total += int(x)
...     if not count:
...         return 0.0
...     return float(total) / count
... 
>>> avgUntilLetter('123a456')
2.0

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

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