擅长:python、mysql、java
<p>您可以考虑使用集合和dict。使用类别名称作为字典的键。所以对于每个<code>p in infile</code>,<code>animals[p[0]].add(p[1])</code>,假设p0,p1是类型和物种。你知道吗</p>
<p>这样做的好处是,如果“Panther”多次以“Cat”的形式出现,则不必检查它是否已存在于“Cat”列表中,因为set类型将确保您拥有一组唯一的元素。你知道吗</p>
<pre><code>>>> from collections import defaultdict
>>> animals = defaultdict(set)
>>> animals['Cat'].add('Panther')
>>> animals
defaultdict(<class 'set'>, {'Cat': {'Panther'}})
>>> animals['Cat'].add('Lion')
>>> animals
defaultdict(<class 'set'>, {'Cat': {'Lion', 'Panther'}})
>>> animals['Cat'].add('Panther')
>>> animals
defaultdict(<class 'set'>, {'Cat': {'Lion', 'Panther'}})
</code></pre>
<p>与使用列表相比:</p>
<pre><code>>>> moreanimals = defaultdict(list)
>>> moreanimals['Cat'].append('Panther')
>>> moreanimals
defaultdict(<class 'list'>, {'Cat': ['Panther']})
>>> moreanimals['Cat'].append('Panther')
>>> moreanimals
defaultdict(<class 'list'>, {'Cat': ['Panther', 'Panther']})
</code></pre>