2012-03-08 169 views
6

IDS Python的方式這似乎是一個很常見的模式:遞增並分配從字典

for row in reader: 
    c1=row[0] 
    if ids.has_key(c1): 
     id1=ids.get(c1) 
    else: 
     currid+=1 
     id1=currid 
     ids[c1]=currid 

我想知道是否有更好的方式來實現這一目標。至於單行if語句去,我可以這樣做了:

id1=ids.get(c1) if ids.has_key(c1) else currid+1 

但後來我堅持用遞增currid,如果在執行別的情況下堅持,堅持C-> ID1到字典如果如果條件通過。

回答

5

如果ID從0開始:

for row in reader: 
    id1 = ids.setdefault(row[0], len(ids)) 

(除此之外:has_key被視爲棄用。使用01的代替d.has_key(x)

+0

這很可愛。 – kindall 2012-03-08 21:51:40

+0

這是完美!一旦它允許我接受,就會接受。 – Sid 2012-03-08 21:52:19

+0

有趣;我今天早些時候發佈了[這個答案](http://stackoverflow.com/a/9619677/166749),實際上[used](https://github.com/larsmans/scikit-learn/commit/86f621b1c738bd2b6d50a663b117500eae2fd63f#L1R79)this成語只有昨天。 – 2012-03-08 21:54:20

-1

用這個代替:

id1 = ids.get(cl, currid + 1) 
0

有點pythonyc,用相同的語義:

for row in reader: 
    c1 = row[0] 
    if c1 not in ids: 
     currid += 1 
     ids[c1] = currid 
    id1 = ids[c1] 
1
currid += c1 not in ids 
id1 = ids.setdefault(c1, currid) 
+0

這不會存儲新的ID。 – 2012-03-08 21:52:18

+0

D'oh!意思是'setdefault'。 – kindall 2012-03-08 21:55:31

4

如果你不介意的變化如何ids定義,那麼你可以用這個(都走在了標準庫):

ids = collections.defaultdict (itertools.count().next) 

用法則很簡單:

print (ids["lol"]) 
+0

很高興知道。我正在建立一個距離矩陣,所以寧願有int ID。也有大量的數據。 – Sid 2012-03-08 21:57:30

+0

非常好,但是這也改變了字典的行爲,因爲它永遠不會再引發'KeyError'。仍然是+1。 – 2012-03-08 21:59:37

+0

@larsmans:不提高'KeyError'是'defaultdict'的要點。 – 2012-03-08 22:03:05