我有这个嵌套循环:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
通过阅读,我期望输出为:
red apple
big banana
tasty cherry
有人可以向我解释为什么我得到吗?
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
我真的很困惑,无法解决!
非常感谢!
答案 0 :(得分:3)
每次循环运行时,循环中的所有事情都会发生(尽管可能会短路或退出循环的事物:封闭函数中的break
,continue
,return
或引发不在本地捕获的异常,或导致程序立即退出的任何事情,例如拔出电源插头:))
内层循环位于外层循环内部(这意味着它们要嵌套),因此整个内层循环在每次通过外层循环时都会一次又一次地发生。
第一次运行外部循环时,x
被设置为'red'
。因此,该值将用于内部循环的每次迭代,并因此与每个y
值配对。在其余的迭代中依此类推。
如果您想要预期的行为,请参阅How to iterate through two lists in parallel?。
答案 1 :(得分:2)
您遍历第一个列表,对于第一个列表中的每个项目,您遍历第二个列表中的所有项目。
就这样...
adj[0], fruits[0] # red apple
adj[0], fruits[1] # red banana
adj[0], fruits[2] # red banana
adj[1], fruits[0] # red apple
等。
您可以尝试使用enumerate
来更清楚地了解幕后发生的事情,但是它有些复杂,最终可能会使事情变得更加困难。
for adj_index, adjective in enumerate(adjectives):
for fruit_index, fruit in enumerate(fruits):
print(f' {adjective} at {adj_index} and {fruit} at {fruit_index}')
正如Karl Knechtel在他的回答中提到的那样,您可以使用zip
来同时遍历列表。
for adj, fruit in zip(adj, fruits):
print(adj, fruit)
答案 2 :(得分:1)
您首先要选择x = 'red'
,然后通过将每个水果分配给内部循环中的y
来打印每个水果。
然后,您选择x = 'big'
,并通过在内部循环中将每个水果分配给y
来将其与每个水果一起打印,等等。
要获得所需的输出,首先需要将列表压缩在一起,然后循环打印。
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
adj_fruits = zip(adj, fruits)
for name in adj_fruits:
print(name[0], name[1])
输出:
red apple
big banana
tasty cherry