2015-07-09 35 views

回答

3

使用计数器识别重复的颜色,并为itertools.count(1)对象创建颜色名称的字典。然后用列表-COMP下一个数字追加到该颜色已经重复颜色,例如:

from collections import Counter 
from itertools import count 

colours=['red','green','blue','yellow','red','red','black','blue','yellow'] 
repeated = {k:count(1) for k, v in Counter(colours).items() if v > 1} 
new_colours = [colour + str(next(repeated[colour])) if colour in repeated else colour for colour in colours] 
# ['red1', 'green', 'blue1', 'yellow1', 'red2', 'red3', 'black', 'blue2', 'yellow2'] 
1
def append_counts(colours): 
    tally = {} 
    result = [] 
    colours.reverse() 
    while colours: 
    colour = colours.pop() 
    tally[colour] = tally.get(colour, 0) + 1 
    result.append("%s%d" % (colour, tally[colour])) 
    return result 

append_counts(['red', 'green', 'blue', 'yellow', 'red', 'red', 'black', 'blue', 'yellow']) 

注:此变异色彩的说法,要小心。

编辑:不变异的颜色参数的另一种方法:

def append_counts(colours): 
    def reducer((counts, hist), colour): 
    hist[colour] = hist.get(colour, 0) + 1 
    counts.append("%s%d" % (colour, hist[colour])) 
    return counts, hist 
    return reduce(reducer, colours, ([], {}))[0] 

append_counts(['red', 'green', 'blue', 'yellow', 'red', 'red', 'black', 'blue', 'yellow']) 
+1

它靠近 - 虽然订单现在颠倒过来了(也许'.pop (0)'?),并从OP示例输出 - 独特的颜色不应附加任何数字 –

+1

不,不弹出(0),它很慢。而是在循环之前colours.reverse()。 – Dalen

+0

呃,现在修好了。 – kzar

0


""" 
This is perhaps not as fast as I would like, but it works according to all specifications. 
+ 1. Updates the list (changes the given list instead of constructing a new one) 
+ 2. Unique items aren't marked with numbers 
""" 

def append_counts (colours): 
    tally = {} 
    get = tally.get 
    for x in colours: 
     v = get(x, 0) 
     tally[x] = v+1+(v==1) 
    for x in xrange(len(colours)-1, -1, -1): 
     c = colours[x] 
     tally[c] -= 1 
     colours[x] = ("%s%d" % (c, tally[c]), c)[tally[c]==0] 

>>> # Example: 
>>> colours = ['red', 'green', 'blue', 'yellow', 'red', 'red', 'black', 'blue', 'yellow'] 
>>> append_counts(colours) 
>>> colours 
['red1', 'green', 'blue1', 'yellow1', 'red2', 'red3', 'black', 'blue2', 'yellow2'] 

1

只是要走火入魔的

[colors[x] + str(len([c for c in colors[:x+1] if c == colors[x]]) if colors[x] in colors[:x] + colors[x+1:] else '') for x in range(len(colors))] 
+0

我只是爱疯了! – Dalen