擅长:python、mysql、java
<p><code>dawg</code>指出了Python中最棒的技巧之一:使用<code>set()</code>从列表中删除重复项。<code>dawg</code>展示了如何通过将每个项添加到一个<code>set</code>中来从头构建唯一列表,这非常完美。但这里有另一种等效的方法,使用<code>list(set())</code>方法生成一个包含重复项的列表和一个不包含重复项的列表:</p>
<pre><code>import csv
in_str = [
'year, category, event',
'1994, Category1, Something Happened 1',
'1994, Category2, Something Happened 2',
'1995, Category1, Something Happened 3',
'1996, Category3, Something Happened 4',
'1998, Category2, Something Happened 5'
]
cdr = csv.DictReader(in_str, skipinitialspace=True)
col = []
for i in cdr:
col.append(i['category'])
# all items in the column...
print(col)
# only unique items in the column...
print(list(set(col)))
</code></pre>