首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python中的数字计数函数需要忽略前导零

python中的数字计数函数需要忽略前导零
EN

Stack Overflow用户
提问于 2018-05-31 08:23:07
回答 3查看 433关注 0票数 0

.123以字符串的形式转换为0.123,因此我的计数结果是(0,0,1)而不是(0,0,0)。我需要忽略前导0,但是我不知道是如何。

def digit_count(n):
    n=str(int(n))
    even_count=0
    odd_count=0
    zero_count=0
    for i in n:

        if int(i)%10 ==0:
            zero_count +=1
        elif int(i) % 2 ==0:
            even_count += 1 
        elif int(i) %2 !=0:
            odd_count +=1

    return(even_count,odd_count,zero_count) 
EN

回答 3

Stack Overflow用户

发布于 2018-05-31 08:44:52

一个老生常谈的解决方案:

def digit_count(n):

    if isinstance(n, float) and str(n).split('.')[0]=='0':
        return (0,0,0)
    else:
        n=str(int(n))


    even_count=0
    odd_count=0
    zero_count=0
    for i in n:

        if int(i)%10 ==0:
            zero_count +=1
        elif int(i) % 2 ==0:
            even_count += 1 
        elif int(i) %2 !=0:
            odd_count +=1

    return(even_count,odd_count,zero_count)
票数 0
EN

Stack Overflow用户

发布于 2018-05-31 18:57:04

def digit_count( n ) :
    ## convert number to string
    n = str( int(n))
    ## declare counts
    even_count, zero_count = 0,0

    for i in n :
        i = int(i)            
    ## case when n = 0.1231            
        if len(n) == 1 and i == 0:
            return (0,0,0)
    ## case when n contains 0
        elif i == 0:
            zero_count += 1
    ## case when n contains even
        elif i != 0  and i%2 == 0 :
            even_count += 1            
    return ( even_count, len(n) - even_count- zero_count, zero_count )

digit_count( 123059.9 )
>> (1,4,1)
digit_count( 0.123 )
>> (0,0,0)
票数 0
EN

Stack Overflow用户

发布于 2019-06-27 09:12:22

对于python 3解决方案来说,像这样的东西怎么样?

    def digit_count(n):
        n=list(str(int(n))); #turn into a list array
        if n[-1] == "0":     #get the first item (leading zeroes).
            n[-1] = "";      #delete it.
        n=''.join(n);        #rejoin as a new string.
        even_count = odd_count = zero_count = 0; #I cleaned this up too.
        for i in n:
            if int(i)%10 == 0:
                zero_count += 1
            elif (int(i) % 2 == 0) ^ (int(i) %2 == 0): #I cleaned this up I hope you don't mind.
                even_count += 1
        return(even_count,odd_count,zero_count) 
    print(digit_count(.123));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50615031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档