【问题标题】:Python - make non-unique items in list unique by adding countPython - 通过添加计数使列表中的非唯一项唯一
【发布时间】:2020-03-24 16:36:54
【问题描述】:

如何通过连接计数来使列表中的项目唯一,每个唯一值从 1 开始?

所以,例如:

sheep, sheep, tiger, sheep, hippo, tiger

变成:

sheep1, sheep2, tiger1, sheep3, hippo1, tiger2

【问题讨论】:

  • 我推荐看一下收藏包中的Counter函数,我相信这会帮助你实现你想要的。

标签: python list count unique


【解决方案1】:

下面是使用 Counter 的方法。

from collections import Counter

s = ["sheep", "sheep", "tiger", "sheep", "hippo", "tiger"]
u = [ f"{a}{c[a]}" for c in [Counter()] for a in s if [c.update([a])] ]

print(u)

['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']

请注意,如果您的字符串可以有数字后缀,这不足以涵盖所有情况(例如,['alpha']*11+['alpha1'] 将重复 'alpha11'

【讨论】:

  • 这对我有用。关于现有数字后缀的要点 - 我不应该有任何后缀,但我会在我的计数之前添加一个下划线以确保它不是问题。
【解决方案2】:

使用defaultdictcount 的组合:

>>> from collections import defaultdict
>>> from itertools import count
>>> s = ["sheep", "sheep", "tiger", "sheep", "hippo", "tiger"]
>>> d = defaultdict(lambda: count(1))
>>> [f'{x}{next(d[x])}' for x in s]
['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']

count 是一个对象,当您对其进行迭代时,它会产生不断增加的数字;调用 next 会为您提供序列中的下一个数字。

defaultdict 会在您每次尝试访问新密钥时创建一个新的 count 实例,同时保存新创建的实例以供您下次看到相同的密钥时使用。

【讨论】:

    【解决方案3】:

    您可以使用简单的for 循环:

    l = ['sheep', 'sheep', 'tiger', 'sheep', 'hippo', 'tiger']
    
    count = {}
    output = []
    for s in l:
        if s in count:
            count[s] += 1
        else:
            count[s] = 1
    
        output.append(f'{s}{count[s]}')
    
    output
    

    输出:

    ['sheep1', 'sheep2', 'tiger1', 'sheep3', 'hippo1', 'tiger2']
    

    【讨论】:

      【解决方案4】:

      我有一个非常相似的输出需要:

      ['sheep', 'sheep1', 'tiger', 'sheep2', 'hippo', 'tiger1']
      

      我在寻找 O(n) 解决方案并扩展字典类时采用了一些不同的方法。

      class IncDict(dict):
          def __missing__(self,key):
              return -1
      
          def __getitem__(self,key):
              val = dict.__getitem__(self,key)
              val+=1
              dict.__setitem__(self,key,val)
              if val==0:
                  return key
              else:
                  return key+str(val)
      
      l = ['sheep', 'sheep', 'tiger', 'sheep', 'hippo', 'tiger']
      uniquify = IncDict()
      [uniquify[x] for x in l]
      

      输出:

      ['sheep', 'sheep1', 'tiger', 'sheep2', 'hippo', 'tiger1']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-04
        • 2016-02-02
        • 2022-08-14
        相关资源
        最近更新 更多