如何在python中返回for循环值并在其他scrip中访问它们

2024-10-02 12:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

通过下面的函数,我可以打印crew_filternode的信息。但是我需要帮助将这些值返回到目标脚本。以及如何在目标脚本中访问它们

def getValuesForNode(self):
   for crew_filter, node in self.getNodes():
       print crew_filter, node

注意:由于crew_filternode将有多个值,我需要将它们存储在元组或字典中


Tags: 函数inself脚本信息node目标for
1条回答
网友
1楼 · 发布于 2024-10-02 12:30:31

如果类Test是在脚本test.py中编写的

test.py

class Test:
    def get_values_for_node(self):
        test_data = (
            (1, 2),
            (3, 4),
            (5, 6)
        )
        for crew_filter, node in test_data:
            yield crew_filter, node

然后,您可以通过上面在另一个脚本中定义的生成器访问您的值,例如foo.py

福比

from test import Test

if __name__ == '__main__':
    test = Test()
    for crew_filter, node in test.get_values_for_node():
        print('{0} - {1}'.format(crew_filter, node))

输出

1 - 2
3 - 4
5 - 6

您可以用数据源(元组或dict)替换vartest_data,如果您想迭代dict,您必须按照以下方式执行:

class Test:
    def get_values_for_node(self):
        test_data = {
            'id':1,
            'name': 'tom',
            'age': 23
        }
        for crew_filter, node in test_data.items():
            yield crew_filter, node

输出

id - 1
name - tom
age - 23

如果您不熟悉yield的用法或generator的概念,可以查看此页面:

What does the "yield" keyword do in Python?

相关问题 更多 >

    热门问题