【发布时间】:2016-05-09 06:21:38
【问题描述】:
我知道如何使用 set() 或两个列表从列表中删除重复项,但是如何维护相同的列表并在末尾添加一个数字以表示重复项?我可以使用 if 来做到这一点,但它不是 pythonic。谢谢大家!!
nome_a = ['Anthony','Rudolph', 'Chuck', 'Chuck', 'Chuck', 'Rudolph', 'Bob']
nomes = []
for item in nome_a:
if item in nomes:
if (str(item) + ' 5') in nomes:
novoitem = str(item) + ' 6'
nomes.append(novoitem)
if (str(item) + ' 4') in nomes:
novoitem = str(item) + ' 5'
nomes.append(novoitem)
if (str(item) + ' 3') in nomes:
novoitem = str(item) + ' 4'
nomes.append(novoitem)
if (str(item) + ' 2') in nomes:
novoitem = str(item) + ' 3'
nomes.append(novoitem)
else:
novoitem = str(item) + ' 2'
nomes.append(novoitem)
if item not in nomes:
nomes.append(item)
print(nomes)
编辑(1):对不起。我为澄清而进行了编辑。
【问题讨论】:
-
我尝试运行代码并没有得到任何输出。列表是否必须保持顺序?
-
不,它没有。我对其进行了编辑以进行澄清。
标签: python list duplicates unique