【问题标题】:Python Dictionary as tuple keys not increasing the valuesPython字典作为元组键不增加值
【发布时间】:2019-10-15 04:20:05
【问题描述】:

我有一个列表列表,例如 transactions = [['1','2','3','4','5','6'],['2','3','6','1','5','10],['6','4','5','6','4','3']] 和一个以元组为键的字典,例如triplets = {(1,2,3): 0, (2,3,4):0} 现在我想检查 triplets 的键是否出现在事务中,因为 (1,2,3) 在第一个嵌套列表中,然后我将更新该键元组的值(它将从 0 变为 1)。如果在另一个列表中找到它,例如它也可以在第二个列表中找到 [2,3,6,1,5,10] 然后它的计数将从 1 增加到 2。这个过程将持续整个 triplets

我写了这段代码,但它并没有增加计数。

    for items in triplets.keys():
        if items in transactions:
            triplets[items] = triplets[items] + 1

如果有人可以正确编辑问题标题,请。我找不到合适的词来问。

【问题讨论】:

    标签: python python-3.x dictionary tuples


    【解决方案1】:

    解决方案

    您可以使用set 来检查triplets 的每个keystransactionssub-lists 的元素的交集。如果交集产生与key 相同的结果,则增加keytriplets 字典中的计数。

    transactions = [[1,2,3,4,5,6],[2,3,6,1,5,10],[6,4,5,6,4,3]]
    transactions = [[str(e) for e in ee] for ee in transactions]
    print('transactions: {}'.format(transactions))
    triplets = {(1,2,3): 0, (2,3,4):0}
    print('triplets: ')
    print('\tBefore Update: {}'.format(triplets))
    
    for key in triplets.keys():
        count = triplets.get(key)
        for t in transactions:
            s = set(list(key))
            count += int(set(t).intersection(s) == s)
        triplets.update({key: count})
    
    print('\tAfter Update: {}'.format(triplets))
    

    输出

    transactions: [['1', '2', '3', '4', '5', '6'], ['2', '3', '6', '1', '5', '10'], ['6', '4', '5', '6', '4', '3']]
    triplets: 
        Before Update: {(1, 2, 3): 0, (2, 3, 4): 0}
        After Update: {(1, 2, 3): 0, (2, 3, 4): 0}
    

    【讨论】:

    • 请再次检查问题。事务中的值是字符串格式,三元组中的值是整数。
    • 如何用字符串检查或整数?或者首先我也必须将整数转换为字符串。
    • 好的。将相应地更新解决方案。谢谢你指出来。虽然这不应该改变基本的解决方案。
    • 您无需更改任何内容。只需应用 for loop as-is
    【解决方案2】:

    您的 if 条件始终评估为 False。

    认为这就是您要寻找的,

    for items in triplets.keys():
        for transaction in transactions:
            if all(x in map(int,transaction) for x in items): #python 2
            #if all(x in list(map(int,transaction)) for x in items): #python 2 and 3
                triplets[items] = triplets[items]+1
    

    输出:

    {(2, 3, 4): 1, (1, 2, 3): 2}
    

    根据问题的变化进行编辑

    【讨论】:

    • 如果一直都是假的。
    • 请再次检查问题。事务中的值是字符串格式,三元组中的值是整数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    相关资源
    最近更新 更多