【问题标题】:Iteration for iteration in a list [duplicate]列表中的迭代迭代[重复]
【发布时间】:2023-03-23 06:10:01
【问题描述】:

假设我有 2 个列表和一个变量:

Name = "Siler City"
List1 = ["Frank", "Beth", "Jose" "Pieter"]
List2 = ["Red", "Green", "Blue", "Purple"]

这是一个复杂问题的简单说明,我不想创建字典是有原因的。这些必须是 2 个单独的列表。我想要的是同时遍历 List1[0] 和 List2[0] 等。所以我想要的结果是

“红房子归弗兰克所有”,“绿房子归贝丝所有”, “蓝房子归何塞所有,”

等等...为什么下面的方法不起作用,什么是更好的策略?

for item in List1:
    if Name == "Siler City":
        for color in List2:
            print("The {} house is owned by {}".format(color, item))

【问题讨论】:

  • 您为 List1 中的每个项目遍历 List2(因为第二个 for 循环在第一个 for 循环的主体内)。

标签: python list if-statement python-3.6 nested-lists


【解决方案1】:

您可以将列表压缩在一起以迭代两者

for list1_elm, list2_elm in zip(List1, List2):
  pass # Remove pass when you add your print statement
  # Do things Here

【讨论】:

  • @mad_ 感谢您的提醒!试图将其余部分留给OP,但我可以看到这可能会令人困惑。添加在占位符中!
  • 注意,它仍然在语法上不正确......你至少需要一个pass
  • @juanpa.arrivillaga 谢谢!立即添加通行证
  • 此代码有效!谢谢!
【解决方案2】:

使用zip:

for item, color in zip(List1, List2):
    print("The {} house is owned by {}".format(color, item))

【讨论】:

  • 忽略最后的评论。这是最简洁的答案。谢谢。
猜你喜欢
  • 2018-04-26
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
  • 2019-07-05
  • 1970-01-01
  • 2019-04-04
相关资源
最近更新 更多