Skip to main content
 首页 » 编程设计

python之嵌套循环和元组

2025年05月04日11jiqing9006

我正在尝试让我的代码在新的

上打印出每个值
cats = ("Tiger","Lion","Cheetah") 
canids = ("Dog","Wolf","Fox") 
reptiles = ("Snake","Crocodile","Iguana") 
animals = (cats, canids,reptiles) 
for i in animals: 
    for j in [0,-1]: 
        print(i[j]) 

但是当我运行它时它不包括列表的第二个值,

Tiger 
Cheetah 
Dog 
Fox 
Snake 
Iguana 

请您参考如下方法:

如果你想遍历索引的范围,你需要使用range。否则,i 只取值 0 和 -1。

for i in animals: 
    for j in range(0, len(i)): # Note the use of `range` here 
        print(i[j]) 

不过,由于 i 本身是一个 tuple,您可以直接对其进行迭代。为了便于阅读,我在这里将 i 重命名为 family。

for family in animals: 
    for animal in family: 
        print(animal) 

两者都有以下输出。

Tiger 
Lion 
Cheetah 
Dog 
Wolf 
Fox 
Snake 
Crocodile 
Iguana