[英]How to combine initialization and assignment of dictionary in Python?
I would like to figure out if any deal is selected twice or more. 我想弄清楚是否有两次或两次以上的交易被选中。
The following example is stripped down for sake of readability. 为了便于阅读,下面的示例已精简。 But in essence I thought the best solution would be using a dictionary, and whenever any deal-container (eg deal_pot_1) contains the same deal twice or more, I would capture it as an error. 但从本质上讲,我认为最好的解决方案是使用字典,每当任何交易容器(例如Deal_pot_1)包含相同交易两次或多次时,我会将其捕获为错误。
The following code served me well, however by itself it throws an exception... 以下代码对我很有帮助,但是它本身会引发异常。
if deal_pot_1:
duplicates[deal_pot_1.pk] += 1
if deal_pot_2:
duplicates[deal_pot_2.pk] += 1
if deal_pot_3:
duplicates[deal_pot_3.pk] += 1
...if I didn't initialize this before hand like the following. ...如果我没有像下面这样事先进行初始化。
if deal_pot_1:
duplicates[deal_pot_1.pk] = 0
if deal_pot_2:
duplicates[deal_pot_2.pk] = 0
if deal_pot_3:
duplicates[deal_pot_3.pk] = 0
Is there anyway to simplify/combine this? 无论如何,有没有简化/组合呢?
There are basically two options: 基本上有两种选择:
Use a collections.defaultdict(int)
. 使用collections.defaultdict(int)
。 Upon access of an unknown key, it will initialise the correposnding value to 0. 访问未知密钥后,它将把对应的值初始化为0。
For a dictionary d
, you can do 对于字典d
,您可以执行
d[x] = d.get(x, 0) + 1
to initialise and increment in a single statement. 在单个语句中初始化和递增。
Edit : A third option is collections.Counter
, as pointed out by Mark Byers. 编辑 :第三个选项是collections.Counter
,由马克·拜尔斯(Mark Byers)指出。
看起来您想要collections.Counter
。
Look at collections.defaultdict . 查看collections.defaultdict 。 It looks like you want defaultdict(int)
. 看来您想要defaultdict(int)
。
So you only want to know if there are duplicated values? 因此,您只想知道是否存在重复的值? Then you could use a set : 然后,您可以使用一组 :
duplicates = set()
for value in values:
if value in duplicates():
raise Exception('Duplicate!')
duplicates.add(value)
If you would like to find all duplicated: 如果您想查找所有重复项:
maybe_duplicates = set()
confirmed_duplicates = set()
for value in values:
if value in maybe_duplicates():
confirmed_duplicates.add(value)
else:
maybe_duplicates.add(value)
if confirmed_duplicates:
raise Exception('Duplicates: ' + ', '.join(map(str, confirmed_duplicates)))
A set is probably the way to go here - collections.defaultdict is probably more than you need. 设置可能是解决问题的方法-collections.defaultdict可能超出了您的需要。
Don't forget to come up with a canonical order for your hands - like sort the cards from least to greatest, by suit and face value. 别忘了为您的手提出规范的顺序-就像按照西装和面值从最小到最大对卡片进行排序。 Otherwise you might not detect some duplicates. 否则,您可能不会检测到某些重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.