实用:python用户输入一个数字,打印每一位数字及其重复的次数(字典练习)

    xiaoxiao2025-01-08  12

    from collections import OrderedDict num = input('>>>') od = OrderedDict() for k in num: od.setdefault(k,0) od[k] += 1 else: for k in num: print('nums:{} count:{}'.format(k,od[k])) print(od)

    运行结果:

    >>>15451 nums:1 count:2 nums:5 count:2 nums:4 count:1 nums:5 count:2 nums:1 count:2 OrderedDict([('1', 2), ('5', 2), ('4', 1)])

    案例变形:

    from collections import OrderedDict num = input('>>>') od = OrderedDict() for k in num: od[k] = od.get(k,0)+1 else: for k in num: print('nums:{} count:{}'.format(k,od[k])) print(od)

    运行结果:

    >>>1141 nums:1 count:3 nums:1 count:3 nums:4 count:1 nums:1 count:3 OrderedDict([('1', 3), ('4', 1)])
    最新回复(0)