擅长:python、mysql、java
<p>您还可以尝试使用<a href="https://docs.python.org/3.7/library/collections.html" rel="nofollow noreferrer">^{<cd1>}</a>对象来跟踪计数,并使用它来跟踪所看到的单词,使用无大小写的单词作为引用。然后,在完成对输入列表的迭代后,如果计数大于1,则更新结果列表,使单词计数的形式为<code>%s (%d)</code>。你知道吗</p>
<p><strong>代码:</strong></p>
<pre><code>from collections import Counter
words = ["paper", "Plastic", "aluminum", "PAPer", "TIN", " paper", "glass", "tin", "PAPER", "Polypropylene Plastic"]
counts = Counter()
result = []
for word in words:
caseless = word.casefold()
if caseless not in counts:
result.append(word)
counts[caseless] += 1
result = ['%s (%d)' % (w, counts[w.casefold()]) if counts[w.casefold()] > 1
else w for w in result]
print(result)
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>['paper (3)', 'Plastic', 'aluminum', 'TIN (2)', ' paper', 'glass', 'Polypropylene Plastic']
</code></pre>