python - Python Dictionary as tuple keys not increasing the values
问题描述
I've a list of list for example transactions = [['1','2','3','4','5','6'],['2','3','6','1','5','10],['6','4','5','6','4','3']]
and a Dict with tuples as keys for example triplets = {(1,2,3): 0, (2,3,4):0}
now i want to check if the keys of triplets
are occurred in the transactions as (1,2,3) is in first nested list then I'll update the values of that key tuple ( It will become 1 from 0). if it is found in another list e.g. it is also available in the second list [2,3,6,1,5,10]
then It's count will increase from 1 to 2. And this process will go on for the whole triplets.
I wrote this code but it's not increasing the count.
for items in triplets.keys():
if items in transactions:
triplets[items] = triplets[items] + 1
if someone can edit the question title properly please. I can't find the right words to ask.
解决方案
解决方案
您可以使用set
检查每个 ofkeys
和 oftriplets
的元素的sub-lists
交集transactions
。如果交集产生与 相同的结果key
,则增加字典 key
中的计数。triplets
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}
推荐阅读
- c# - 为什么计算绑定工作比 IO 绑定工作在更少的线程上运行
- html - 如何在 AWS S3 上刷新我的网站上的数据?
- string - 如何在 Marie 中修剪字符串末尾的空格?
- android - 在嵌套滚动视图中的 Recyclerview 中获取滚动
- java - 如果由 maven-assembly-plugin 构建,则附加主要工件
- android - 外部Sqlite数据库,无法插入数据库,android studio
- sql - 选择数字组合与整数 SQL 的一部分匹配的位置
- ios - 如何在 Swift 中创建延迟实际应用程序加载时间的自定义启动屏幕?
- swift - Swift UITableView AccessoryType(复选标记)
- reactjs - 成功部署 Firebase 后的空白页面