我想在T1中讀取並將它寫爲T2(注意兩者都是.csv)。 T1包含重複的行;我不想在T2中重複寫入。Filter-Out重複表條目
T1
+------+------+---------+---------+---------+
| Type | Year | Value 1 | Value 2 | Value 3 |
+------+------+---------+---------+---------+
| a | 8 | x | y | z |
| b | 10 | q | r | s |
+------+------+---------+---------+---------+
T2
+------+------+---------+-------+
| Type | Year | Value # | Value |
+------+------+---------+-------+
| a | 8 | 1 | x |
| a | 8 | 2 | y |
| a | 8 | 3 | z |
| b | 10 | 1 | q |
| ... | ... | ... | ... |
+------+------+---------+-------+
目前,我有這樣的速度奇慢的代碼過濾掉重複:
no_dupes = []
for row in reader:
type = row[0]
year = row[1]
index = type,age
values_list = row[2:]
if index not in no_dupes:
for i,j in enumerate(values_list):
line = [type, year, str(i+1), str(j)]
writer.writerow(line) #using csv module
no_dupes.append(index)
我不能exagerate這個代碼是如何緩慢時,T1變大。
當我寫入T2時,是否有更快的方式從T1中過濾出重複項?
在最低限度,要添加每次在循環中將'index'指向'no_dupes'列表。因此:(1)將'no_dupes'改爲'set'並且(2)在每個循環中僅將'index'添加到'no-dupes'一次。 – hughdbrown 2013-04-09 19:45:12