1

我是python新手,有一个简单的问题。

我有一个列表列表

tempList = [ ['a', 'b', 'c', 'a', 'd', 'b', 'a'], ['a', 'c', 'd', 'c', 'd'] ]

我想用增量数字重命名所有后续重复项,例如:

tempList= [ ['a', 'b', 'c', 'a_1', 'd', 'b_1', 'a_2'], ['a', 'c', 'd', 'c_1', 'd_1']]

我知道如何为平面列表执行此操作,但我无法找到列表列表的解决方案。谁能给我一个关于如何做到这一点的指针?我尝试的代码如下,似乎不起作用。

for i in range(0, len(tempList)):
    counts = Counter(tempList[i])
    print(Counter(tempList[i]))
    val = 0
    for s,num in counts.items():
        if num > 1:
            counts[s] = val
            val += 1
        else:
            counts[s] = 0
    tempList = [x if counts[x]==0 else x + str(counts[x]) for x in tempList[i]]
4

1 回答 1

0

这是保留顺序的可能解决方案:

def foo(l):
    d = {}
    for i in range(len(l)):
        if l[i] in d:
            d[l[i]] += 1
            l[i] = l[i] + '_' + str(d[l[i]])
        else:
            d[l[i]] = 0
    return l

list_of_lists = [ ['a', 'b', 'c', 'a', 'd', 'b', 'a'], ['a', 'c', 'd', 'c', 'd'] ]
list_of_lists = [foo(x) for x in list_of_lists]
于 2020-02-24T05:09:12.530 回答