如何使用功能输入更有效?

时间:2017-12-20 13:23:53

标签: python python-3.x python-2.7

我有一个功能

init_from_checkpoint(
ckpt_dir_or_file,
assignment_map)

其中assignment_map支持以下语法:

  

' checkpoint_scope_name /':' scope_name /' - 将使用匹配的张量名称从checkpoint_scope_name加载当前scope_name中的所有变量。

例如,

init_from_checkpoint('/tmp/model.ckpt',
                     {'old_scope_1/var1': 'new_scope_1/var1',
                      'old_scope_1/var2': 'new_scope_1/var2'})

现在,我有两个列表

old_scope_1_list=[old_scope_1/var1, old_scope_1/var2, ...,old_scope_1/var100]
new_scope_1_list=[new_scope_1/var1, new_scope_1/var2, ...,new_scope_1/var100]

如何使用init_from_checkpointold_scope_1_list调用函数new_scope_1_list以在python中有效地调用函数?我目前的解决方案是在不使用这两个列表的情况下写下100行,但它看起来效果不佳

init_from_checkpoint('/tmp/model.ckpt',
                         {'old_scope_1/var1': 'new_scope_1/var1',
                          'old_scope_1/var2': 'new_scope_1/var2',
                          ...
                          'old_scope_1/var100': 'new_scope_1/var100'})

1 个答案:

答案 0 :(得分:4)

您可以使用zip function来生成old_scope_1_list和new_scope_1_list中的对列表。然后在这些对上使用dict来创建所需的映射。

In [67]: old_scope_1_list=['old_scope_1/var1', 
'old_scope_1/var2','old_scope_1/var100']
...: new_scope_1_list=['new_scope_1/var1', 
'new_scope_1/var2','new_scope_1/var100']


In [68]: zip(old_scope_1_list, new_scope_1_list)
Out[68]: <zip at 0x7f4dd084c748>

In [69]: x = zip(old_scope_1_list, new_scope_1_list)

In [70]: dict(x)
Out[70]: 
{'old_scope_1/var1': 'new_scope_1/var1',
'old_scope_1/var100': 'new_scope_1/var100',
'old_scope_1/var2': 'new_scope_1/var2'}

所以在你的情况下,代码将是:

init_from_checkpoint('/tmp/model.ckpt', dict(zip(old_scope_1_list, new_scope_1_list)))