如何在Python中修复此嵌套的for循环

时间:2019-05-15 16:31:31

标签: python for-loop jupyter-notebook nested-loops

我正在编写一个循环,以遍历2个列表并从中打印句子,但是它不起作用。

我尝试过更改语法,但是没有任何效果。

states = ["virginia", "new jersey", "north carolina", "california"]
capitals = ["richmond", "trenton", "raleigh", "sacramento"]

for x, name in enumerate(states):
    for y name in enumerate(capitals):
        print("The capital of " + states[x] + "is " + capitals[y] + ".")

这是我不断遇到的错误。

File "<ipython-input-11-9f2d009ec38f>", line 2
    for y name in enumerate(capitals):
             ^
SyntaxError: invalid syntax

5 个答案:

答案 0 :(得分:2)

无效的语法是因为您在y和名称之间缺少','。

无论如何,您都可以使用内置函数zip

for state, capital in zip(states, capitals):
    print("The capital of " + state + "is " + capital)

答案 1 :(得分:0)

您在第二个for循环中错过了一个“,” for y, name in enumerate(capitals):

答案 2 :(得分:0)

我认为这里不需要嵌套的for循环。您的列表长度相同,因此enumerate()已经在告诉您索引。我可以将其简化为:

states = ["virginia", "new jersey", "north carolina", "california"]
capitals = ["richmond", "trenton", "raleigh", "sacramento"]

for x, name in enumerate(states):
    print("The capital of " + name + " is " + capitals[x] + ".")

哪种产量:

  

弗吉尼亚州的首都是里士满。

     

新泽西的首都是特伦顿。

     

北卡罗来纳州的首都是罗利。

     

加利福尼亚的首都是萨克拉曼多。

答案 3 :(得分:0)

您应该尝试以下操作:

states = ["virginia", "new jersey", "north carolina", "california"]
capitals = ["richmond", "trenton", "raleigh", "sacramento"]

for state, capital in zip(states, capitals):
    print("The capital of " + state + "is " + capital + ".")

输出:

The capital of virginiais richmond.
The capital of new jerseyis trenton.
The capital of north carolinais raleigh.
The capital of californiais sacramento.

答案 4 :(得分:0)

这里不需要嵌套循环,因为您的数据中具有一对一的关系(每个状态都具有1个大写字母,每个资本都具有1个状态)。您可以使用zip创建对,或者如果您希望在for循环中使用索引值,可以执行以下操作:

states = ["virginia", "new jersey", "north carolina", "california"]
capitals = ["richmond", "trenton", "raleigh", "sacramento"]
for i in range(len(states)):
    print("The capital of "+states[i]+" is "+capitals[i])

或使用所谓的f-strings

states = ["virginia", "new jersey", "north carolina", "california"]
capitals = ["richmond", "trenton", "raleigh", "sacramento"]
for i in range(len(states)):
    print(f"The capital of {states[i]} is {capitals[i]}")

两种情况下的输出均为:

The capital of virginia is richmond
The capital of new jersey is trenton
The capital of north carolina is raleigh
The capital of california is sacramento

请注意,如果states的元素数等于capitals的元素数,我的方法将正常工作。