count letter and show in list

后端 未结 3 756
小鲜肉
小鲜肉 2020-12-22 08:12

I need to receive a string from the user, present it in list so each organ in the list contains [the letter, the number it repeat in a row].

I thought my code is goo

3条回答
  •  离开以前
    2020-12-22 08:37

    You can do this very easily using defaultdict:

    import collections
    
    defaultdict=collections.defaultdict
    count=defaultdict(int)
    string="hello world"
    for x in string:
        count[x]+=1
    

    To show it in a list you can do:

    count.items()
    

    which in this case would return:

    [(' ', 1), ('e', 1), ('d', 1), ('h', 1), ('l', 3), ('o', 2), ('r', 1), ('w', 1)]
    

提交回复
热议问题