代码之家  ›  专栏  ›  技术社区  ›  Maxxx

基于元素在列表中出现的次数打印输出

  •  1
  • Maxxx  · 技术社区  · 6 年前

    目前,我有一个列表包含:

    lst = [[2],[2,2],[2,2,2,3,3],[2,3,5,5]]
    

    2^1             #since there is only one '2'   
    2^2             #since there are two '2' in the first list
    2^3 | 3^2       #three '2' and two '3'
    2^1 | 3^1 | 5^2 #one '2', one '3' and two '5'
    

    我试过:

    for i in range(len(lst)):
        count = 1
        if len(lst[i]) == 1:
            print(str(lst[i][0]) + "^" + str(count))
        else:
            for j in range(len(lst[i])-1):
                if lst[i][j] == lst[i][j+1]:
                    count+=1
                else:
                    print(str(lst[i][j]) + "^" + str(count) + " | " +str(lst[i][j+1]) + "^" +str(count)) 
            if count == len(lst[i]):
                print(str(lst[i][j]) + "^" + str(count))
    

    但是我得到了

    2^1
    2^2
    2^3 | 3^3
    2^1 | 3^1
    3^1 | 5^1
    

    希望能帮上忙

    2 回复  |  直到 6 年前
        1
  •  2
  •   hiro protagonist    6 年前

    一个简单的变体 itertools.Counter

    from collections import Counter
    
    for sublist in lst:
        c = Counter(sublist)
        print(' | '.join(f'{number}^{mult}' for number, mult in c.items()))
    

    这让 Counter

    这个 对象的工作方式与词典类似,如下所示(列表中的最后一项):

    c = Counter({5: 2, 2: 1, 3: 1})
    

    就像一个 dict 您可以在 key, value 成对使用 c.items() . 格式字符串 f'{number}^{mult}' 5^2 那就是 join ed使用分隔符 ' | ' .

        2
  •  0
  •   vash_the_stampede    6 年前

    你可以用 itertools.groupby网站 唯一的问题是 | 在印刷品上

    from itertools import groupby
    
    lst = [sorted(i) for i in lst]
    for i in lst:
        for k, g in groupby(i):
            print('{}^{} | '.format(k, len(list(g))), end='')
        print()
    
    2^1 | 
    2^2 | 
    2^3 | 3^2 | 
    2^1 | 3^1 | 5^2 |