count letter and show in list

后端 未结 3 755
小鲜肉
小鲜肉 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:34

    Use itertools.groupby() here:

    >>> from itertools import groupby
    >>> [[k, len(list(g))] for k, g in groupby("baaaaab")]
    [['b', 1], ['a', 5], ['b', 1]]
    

    Or without using libraries:

    strs = raw_input("Enter a string:")
    lis = []
    for x in strs:
       if len(lis) != 0:
          if lis[-1][0] == x:
             lis[-1][1] += 1
          else:
             lis.append([x, 1])
       else:
           lis.append([x, 1])         
    print lis                   
    

    output:

    Enter a string:aaabbbcccdef
    [['a', 3], ['b', 3], ['c', 3], ['d', 1], ['e', 1], ['f', 1]]
    
    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2020-12-22 08:47

    Simpler variant of Aswini's code:

    string = raw_input("Enter a string:")
    lis = []
    for c in string:
        if len(lis) != 0 and lis[-1][0] == c:
            lis[-1][1] += 1
        else:
            lis.append([c, 1]) 
    
    print lis  
    
    0 讨论(0)
提交回复
热议问题