繁体   English   中英

如何仅运行一次 python 嵌套 for 循环外循环

[英]How to run a python nested for loop outer loop only once

我试图练习嵌套的 for 循环,并且我试图让外循环每次只运行一次。 我尝试将 if 与索引一起使用。 下面的原始代码将 adj 中的所有内容重复 3 次,而我只希望它重复一次。

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)

这里的 output 是:

红苹果 红香蕉 红樱桃 大苹果 大香蕉 大樱桃 美味的苹果 美味的香蕉 美味的樱桃

虽然我只希望它是红苹果、大香蕉和美味的樱桃。 所以我尝试在下面执行以下代码,但我不断收到一般语法错误。

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]


for x in adj:
    print(x)
    a = adj.index(x)
    print(a)
    for y in fruits:
        b = fruits.index(y)
        print(b)
        if int(a) = int(b):
            print(x, y)

有没有人有任何关于如何 go 的建议或提示? 我正在尝试为我的项目做类似的事情,但我无法将 x 变量设置为不重复每个 y 的重复?

这是一个可以使用zip()的完美示例:

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x, y in zip(adj, fruits):
    print(x, y)

Output:

red apple
big banana
tasty cherry

在这种情况下,您应该使用内置的zip() function,如下例所示:

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x, y in zip(adj, fruits):
    print(x, y)

请注意,您可以将zip()与两个以上的 arguments 一起使用

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
colors = ["green", "yellow", "red"]

for x, y, z in zip(adj, fruits, colors):
    print(x, y, z)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM