【问题标题】:How can I have multiple different values to iterate through in the same for statement?如何在同一个 for 语句中迭代多个不同的值?
【发布时间】:2021-08-27 21:00:29
【问题描述】:

Error 返回 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
------------------------------------------
"""

【问题讨论】:

  • zip 在这里很有用。遍历zip(account,("First Name", "Last Name", "Age"))。这似乎是您在没有意识到的情况下尝试做的事情。您似乎有太多的循环级别,这没有意义。
  • 我同意。我确定您不首先想要所有“名字”,然后是所有“姓氏”等。因此,将for meta 作为最外层循环可能是错误的。

标签: python python-3.x


【解决方案1】:

我认为您正在寻找的是:

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("------------------------------------------")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多