首页 > 解决方案 > 如何在同一个 for 语句中迭代多个不同的值?

问题描述

错误返回 ValueError: too many values to unpack (expected 2)

accounts = [["Tom", "Boyle", "23"]]
for meta in "First Name", "Last Name", "Age":
    for account in accounts:
        # The line below is what I have trouble with
        for info, meta in account, ("First Name", "Last Name", "Age"): 
            print(meta + ": " + info)
            print("------------------------------------------")

            
""" Expected Output:
First Name: Tom
Last Lame: Boyle
Age: 23
------------------------------------------
"""

标签: pythonpython-3.x

解决方案


我认为您正在寻找的是:

accounts = [["Tom", "Boyle", "23"]]
meta_list = ["First Name", "Last Name", "Age"]
for account in accounts:
    for meta, info in zip(meta_list,account): 
        print(meta + ": " + info)
    print("------------------------------------------")

推荐阅读