Python在for循环中使用列表中的变量

时间:2018-04-23 09:22:56

标签: python python-3.x

我试图找出如何在迭代过程中将值替换为列表。需要这个的原因是这是测试代码,最终将有最多15/20 API调用来构建数千个table_2_details条目。

代码:

table1 = ['table_1', 'getpost', 'url_1_<project_id>', 'filename_1']
table2 = ['table_2', 'getpost', 'url_2_<project_id>', 'filename_2']

api_calls = [table1, table2]

# Special treatment
table2_details = ['table_2_details', 'getpost', 'url_2_details_<project_id>_<checklist_id>', 'filename_2_details']

projects = ['proj1', 'proj2', 'proj3']
checklists = ['check1', 'check2', 'check3']

for project_id in projects:
    print(f"\n{project_id}")
    for call in api_calls:
        print(call[2])
        if call[0] == "table_2":
            for checklist_id in checklists:
                print(table2_details[2])

当前输出:

proj1
url_1_<project_id>
url_2_<project_id>
url_2_details_<project_id>_<checklist_id>
url_2_details_<project_id>_<checklist_id>
url_2_details_<project_id>_<checklist_id>

proj2
url_1_<project_id>
url_2_<project_id>
url_2_details_<project_id>_<checklist_id>
url_2_details_<project_id>_<checklist_id>
url_2_details_<project_id>_<checklist_id>

proj3
url_1_<project_id>
url_2_<project_id>
url_2_details_<project_id>_<checklist_id>
url_2_details_<project_id>_<checklist_id>
url_2_details_<project_id>_<checklist_id>

我需要在&lt;&gt;

中显示的project_id和checklist_id中替换

我是Python的新手,所以如果这是疯了,请指出我正确的方向,以便我可以学习。

感谢您的帮助,

3 个答案:

答案 0 :(得分:0)

您可以使用字符串格式来执行此操作,例如将格式化序列放在字符串中,如下所示:

table2_details = ['table_2_details', 'getpost', 'url_2_details_{project_id:}_{checklist_id:}', 'filename_2_details']

然后在使用任何字符串之前,按照以下格式运行它们:

for arg in table2_details:
    print(arg.format(project_id='foo', checklist_id='bar'))

答案 1 :(得分:0)

您可以使用

等列表中的数据动态构建url
table2_details = ['table_2_details', 'getpost', 'url_2_details', 'filename_2_details']
...

for checklist_id in checklists:
  url = table2_details[2] + "_" + project_id + "_" + checklist_id
  print(url)
  # do something with this url

答案 2 :(得分:0)

使用格式打印。

table1 = ['table_1', 'getpost', 'url_1_{0}', 'filename_1']
table2 = ['table_2', 'getpost', 'url_2_{0}', 'filename_2']

api_calls = [table1, table2]

# Special treatment
table2_details = ['table_2_details', 'getpost', 'url_2_details_{0}_{1}', 'filename_2_details']

projects = ['proj1', 'proj2', 'proj3']
checklists = ['check1', 'check2', 'check3']

for project_id in projects:
    print "{}".format(project_id)
    for call in api_calls:
        print(call[2].format(project_id))
        if call[0] == "table_2":
            for checklist_id in checklists:
                print(table2_details[2].format(project_id, checklist_id))