lis中的迭代

2024-04-25 21:04:44 发布

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

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

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

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

"The Red house is owned by Frank", "The Green house is owned by Beth", "The Blue house is owned by Jose,"

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

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

Tags: thefranknamecity列表byisred
2条回答

使用^{}

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

您可以将列表压缩到一起,以便在两者之间进行迭代

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

相关问题 更多 >