更新列表中的特定项目

时间:2016-11-03 17:52:06

标签: python list

我有以下输入:

'lesson*lesson*practice*lesson*quiz*practice'

这是所需的输出:

'lesson1*lesson2*practice1*lesson3*quiz*practice2'

因此,如果列表中有任何项目重复,我想在事件中附加1,2,3 ....为此,我提出了以下代码:

line = 'lesson*lesson*practice*lesson*quiz*practice'
line1 = line

def list_to_dict(li):  
    dct = {}  
    for item in li.split('*'):  
        if dct.has_key(item):  
            dct[item] = dct[item] + 1  
        else:  
            dct[item] = 1  
    return dct

for item in list_to_dict(line).keys():
    counter = 1
    if list_to_dict(line)[item] > 1:
        indices = [i for i, x in enumerate(line.split('*')) if x == item]
        for idx, _ in enumerate(line1[indices]):
            line1[idx] = line1[idx] + str(counter)
            counter = counter + 1

print line1
print line

但是这段代码给了我以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-187-a85290a89eea> in <module>()
      6     if list_to_dict(line)[item] > 1:
      7         indices = [i for i, x in enumerate(line) if x == item]
----> 8         for idx, _ in enumerate(line1[indices]):
      9             line1[idx] = line1[idx] + str(counter)
     10             counter = counter + 1

TypeError: string indices must be integers, not list

请有人能帮助获得所需的输出吗?

如果您认为我的算法实现这一点并不好,我也欢迎任何新想法。

2 个答案:

答案 0 :(得分:2)

我没有尝试过您的代码,但我怀疑使用dict会导致订购问题?这是一个解决方案:

from collections import Counter

def add_counts_to_words(s):
    words = s.split('*')
    totals = Counter(words)
    counts = Counter()
    result = []
    for word in words:
        if totals[word] > 1:
            counts.update([word])
            result.append('%s%d' % (word, counts[word]))
        else: # singleton
            result.append(word)
    return '*'.join(result)

print add_counts_to_words('lesson*lesson*practice*lesson*quiz*practice')

答案 1 :(得分:0)

不确定您为什么要重新发明collections.Counter

但是你过分复杂了你的答案

from collections import Counter

line = 'lesson*lesson*practice*lesson*quiz*practice'
line_list = line.split('*')

counter = Counter()
output_list = []
for elem in line_list:
    counter.update((elem, 1))
    output_list.append(''.join((elem, str(counter[elem]))))

'*'.join(output_list)

输出:

'lesson1*lesson2*practice1*lesson3*quiz1*practice2'