在更新字典值时施加条件IF语句

问题描述 投票:0回答:2

我正在确定元组中出现的前两个值之间共享的最大值(元组中的第三个值)。

我创建了一个defaultdict,它利用元组的前两个值的排序后的并置值作为dic键,并将dic值分配为元组的第三个值。

我如何施加条件,以便当我遇到相同的配对时,用更大的值替换dic值?我只想仔细阅读一下清单,以提高效率。

users = [
    ('2','1',0.7),
    ('1','2', 0.5),
    ('3','2', 0.99),
    ('1','3', 0.78),
    ('2','1', 0.5),
    ('2','3', 0.99),
    ('3','1', 0.78),
    ('3','2', 0.96)]

#The above list is much longer ~10mill+, thus the need to only read through it once. 
#Current code

from collections import defaultdict

user_pairings = defaultdict()

for us1, us2, maxval in users:
    user_pairings[''.join(sorted(us1+us2))] = maxval ##-> How to impose the condition here? 

print(user_pairings)

编辑刚刚意识到我的方法存在一个重大缺陷。如果用于键的值不是一位数字,则由于使用,我的输出将不是正确的结果sorted

python dictionary
2个回答
0
投票

要做的是替换:

    user_pairings[''.join(sorted(us1+us2))] = maxval

使用:

    key = ''.join(sorted(us1 + us2))
    user_pairings[key] = max(maxval, user_pairings[key] if key in user_pairings else 0)

0
投票

您可以使用字典get方法来检查字典中是否已存在key,如果不存在则返回0,然后将该值和当前值分配给max key

user_pairings = {}

for us1, us2, maxval in users:
    key = ''.join(sorted([us1, us2]))
    user_pairings[key] = max(maxval, user_pairings.get(key, 0))

print(user_pairings)

输出示例数据:

{'13': 0.78, '23': 0.99, '12': 0.7}

注意,在将us1us2转换为字符串时,sorted可以将其拆分回一个列表中,没有多大意义。也可以只使用列表[us1, us2]开始。

© www.soinside.com 2019 - 2024. All rights reserved.