【问题标题】:Using tuples as dict keys and updating value使用元组作为字典键并更新值
【发布时间】:2015-01-28 03:25:43
【问题描述】:
nodes_g = {}    
with open("calls.txt") as fp3:
    for line in fp3:
        rows3 = line.split(";")
        x, node1, node2, sec, y = line.split(";")
        if node1 not in nodes_g:
            nodes_g[node1, node2] = int(rows3[3])
        elif node1 in nodes_g and node2 in nodes_g:
            nodes_g[node1, node2] += int(rows3[3])

    print(nodes_g)

我现在有这个,其中 node1 是呼叫号码,node2 是接收号码,sec 或 rows3[3] 是两个号码之间通话的秒数。我想使用文件的第三行更新 dict 的值(通话秒数),但是不是更新它,而是用下一行 3 值替换它,依此类推。

calls.txt 文件的链接:http://pastebin.com/RSMnXDtq

【问题讨论】:

    标签: python python-3.x dictionary tuples


    【解决方案1】:

    这是因为使用 nodes_g[node1,node2] 隐式地将键转换为元组 (node1, node2)。话虽如此,条件检查node1 not in nodes_g 始终为假,因为您将元组或对存储为键而不是单个节点。

    您应该改为:

    from collections import Counter
    
    nodes_g = Counter()
    
    with open("test.txt") as fp3:
        for line in fp3:
            x, node1, node2, sec, y = line.split(";")
            # Missing keys default to 0.
            nodes_g[node1, node2] += int(sec)
    
    print(nodes_g)
    

    【讨论】:

    • 如果说 #1 和 #2 通话并通话 20 秒,然后 #1 和 #2 再次通话并通话 30 秒,我该怎么做;所以它会变成这样: {('#1','#2') : 50} ?因为在我看来,这并不能说明 #1 和其他数字之间的所有可能性。此外,将元组对存储为键正是我想要的。
    • @no_sleep 如果在您的文件中,#1#2 交谈了 10 秒,然后是 20 秒,甚至更晚 #2#1 交谈了 10 秒,然后结果将是{(#1, #2): 30, (#2, #1): 10}。如果要将两种情况合并为一个,请使用 frozenset 集合作为键:nodes_g[frozenset([node1, node2])] += int(sec)
    • 它说 freezeset 最多期望一个参数,我给它两个。
    • @no_sleep 你需要给它一个可迭代的,例如list。这就是我在上一条评论中所做的。
    • 谢谢!有用!另外,有什么方法可以代替使用元组中的数字而只分配一个 int 吗?比如说#1 =(一些电话号码);我希望它是 #1=1
    猜你喜欢
    • 2020-09-25
    • 2018-09-22
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2012-02-20
    • 2013-11-01
    • 2019-10-25
    相关资源
    最近更新 更多