【发布时间】:2021-09-06 09:03:06
【问题描述】:
我有两本词典,
data1 = {
"key": [
{
"id": "key1",
"name": "key1"
},
{
"id": "key2",
"name": "key2"
},
{
"id": "key3",
"name": "key3"
},
]
}
data2 = {
"key": [
{
"id": "key2"
"name": "TEST key2"
},
{
"id": "key1",
"name": "TEST key1"
},
]
}
我正在使用以下代码制作data1 和data2 中key 列表中具有匹配id 的对象的元组列表
common_keys = [
(each_data1_key, each_data2_key)
for each_data1_key in data1.get("key", [])
for each_data2_key in data2.get("key", [])
if each_data1_key.get("id") == each_data2_key.get("id")
]
# Example result = [({"id":"key1", "name": "key1"}, {"id": "key1", "name": "TEST key1"}), ...]
现在我想使用这些元组在 threadPoolExecutor 的 map 函数中进一步处理。目前,我正在使用以下代码,
def func(object1, object2):
"""
func is being run in the thread to do some task parallelly with object1 and object2
"""
<SOME CODE HERE> ...
def myfunc(common_keys):
if common_keys:
with ThreadPoolExecutor(max_workers=10) as executor:
executor.map(lambda x: func(*x), common_keys)
# func is a function that accepts 2 objects as parameters
# since we are sending tuple of the object in threads, in order to process some task
我的任务是通过减少循环来优化代码(我已经使用嵌套的for循环来查找common_keyslist`
谁能帮我找到任何解决方案,为了获得具有相同 id 的对象的元组列表,我不需要使用嵌套循环(或者,使用另一种优化方式)?
【问题讨论】: