[英]Using setdefault, but not wanting to reassign back to map/dict
我使用setdefault來計數這樣的實例(這是簡化版本):
user_to_count_map = {}
for username in list_of_usernames:
x = user_to_count_map.setdefault(username, 0)
x += 1
user_to_count_map[username] = x + 1
for username in sorted(usernmae_to_count_map):
print username, user_to_count_map[username]
我不喜歡分配回地圖,因為實際代碼會隨着多個計數的增加而變得更加復雜。 但我似乎確實需要這樣做。 有沒有簡單的方法可以解決?
您可以將counter設為包含一個元素的列表,從而有效地使其可變:
user_to_count_map = {}
for username in list_of_usernames:
x = user_to_count_map.setdefault(username, [0])
x[0] += 1
for username, counter in sorted(user_to_count_map.items()):
print username, counter[0]
我不確定這是否會使您的代碼更具可讀性,因為顯式比隱式更好。
或者,如果使用python 2.7或更高版本(或使用方便的backport ),則可以使用Counter
對象 :
from collections import Counter
user_to_count_map = Counter()
for username in list_of_usernames:
user_to_count_map[username] += 1
for username, counter in sorted(user_to_count_map.items()):
print username, counter[0]
請注意,通過使用“ Counter
您將擁有一個字典,該字典會自動為您提供默認值0。否則它的作用就像是一個存儲整數值的字典,因此您可以按自己喜歡的任何方式增加和減少這些值(包括加1以上)。
使用defaultdict
也可以在collections模塊中獲得相同的效果,但是請注意Counter
類提供了功能。 defaultdict
存在於python 2.5及更高版本中; 例:
from collections import defaultdict
user_to_count_map = defaultdict(lambda: 0)
for username in list_of_usernames:
user_to_count_map[username] += 1
或者,您可以完全省去setdefault,因為無論如何總要分配給映射:
user_to_count_map = {}
for username in list_of_usernames:
x = user_to_count_map.get(username, 0)
x += 1
user_to_count_map[x] = x
for username, counter in sorted(user_to_count_map.items()):
print username, counter[0]
如果您不喜歡setdefault並且始終以0開頭,則可以執行以下操作:
from collections import defaultdict
user_to_count_map = defaultdict(lambda: [0])
for username in list_of_usernames:
# no set_default
user_to_count_map[username][0] += value
for username, counter in sorted(user_to_count_map.items()):
print username, counter[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.