【问题标题】:How to enumerate-label the elements of a list in python? [duplicate]如何枚举标记python中列表的元素? [复制]
【发布时间】:2021-03-25 06:30:12
【问题描述】:

有人可以帮我如何枚举列表的元素来标记元素的出现次数,即,

list_in = ['a','b','c']
list_out =  ['a-1','b-1','c-1']
list_in = ['a','b','a']
list_out =  ['a-1','b-1','a-2']
list_in = ['a','a','a']
list_out =  ['a-1','a-2','a-3']

【问题讨论】:

标签: python


【解决方案1】:

你可以统计list_in中每一项的出现次数:

list_in1 = ['a', 'b', 'c']
list_in2 = ['a', 'b', 'a']
list_in3 = ['a', 'a', 'a']


def reformat(list_in):
    counts = {item: list(range(list_in.count(item))) for item in set(list_in)}
    out = [f"{item}-{counts[item].pop(0)+1}" for item in list_in]
    print(out)


for list_in in (list_in1, list_in2, list_in3):
    reformat(list_in)

输出:

['a-1', 'b-1', 'c-1']
['a-1', 'b-1', 'a-2']
['a-1', 'a-2', 'a-3']

【讨论】:

  • 这个答案更好,OP应该接受这个。
【解决方案2】:

这是一种方法:

list_in = ['a','b','c']

lst_new = [list_in[x]+'-'+str(list_in[0:x+1].count(list_in[x])) for x in range(len(list_in))]

print(lst_new)

【讨论】:

    【解决方案3】:

    您可以计算列表中每个字母前面的字母数量,并将结果格式化为列表理解:

    list_in  = ['a','b','a']
    
    list_out = [f"{c}-{list_in[:i].count(c)+1}" for i,c in enumerate(list_in)]
    
    # ['a-1', 'b-1', 'a-2']
    

    【讨论】:

      【解决方案4】:

      我写了一个,但它与原始列表中的顺序不同。

      >>> from collections import Counter
      
      >>> def enum(listy):
      >>>     counter = Counter(listy)
      >>>     final = []
      >>>     for val in range(len(counter)):
      >>>         alp, times = counter.popitem()
      >>>         temp = []
      >>>         for p in range(1, times+1):
      >>>             temp.append(alp+'-'+str(p))
      >>>         final.extend(temp)
              
      >>>     return final
      
      >>> list_in = ['a','b','a']
      
      >>> print(enum(list_in))
      ['b-1', 'a-1', 'a-2']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-04
        • 2011-12-28
        • 1970-01-01
        • 2023-03-19
        • 2012-04-20
        • 2022-12-11
        • 2017-10-28
        • 1970-01-01
        相关资源
        最近更新 更多