【问题标题】:Nested Loops And Tuples嵌套循环和元组
【发布时间】:2018-09-11 18:06:00
【问题描述】:

我试图让我的代码打印出新的每个值

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

【问题讨论】:

  • 你希望for j in [0,-1]: 做什么?
  • 它不仅仅是第二个值。您正在迭代 0 和 -1,这是您的元组索引的第一个和最后一个元素。因此,甚至不考虑中间的任何元素!

标签: python for-loop tuples


【解决方案1】:

如果你想遍历一个索引范围,你需要使用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

【讨论】:

    【解决方案2】:

    j 将是 0-1,即索引列表时的第一个和最后一个值。

    你可以简单

    cats = ("Tiger", "Lion", "Cheetah")
    canids = ("Dog", "Wolf", "Fox")
    reptiles = ("Snake", "Crocodile", "Iguana")
    animal_lists = (cats, canids, reptiles)
    for animal_list in animal_lists:
        for animal in animal_list:
            print(animal)
    

    【讨论】:

      【解决方案3】:

      你可以chain不同的迭代器

      from itertools import chain
      list(chain(*animals))
      

      输出

      ['Tiger',
       'Lion',
       'Cheetah',
       'Dog',
       'Wolf',
       'Fox',
       'Snake',
       'Crocodile',
       'Iguana']
      

      【讨论】:

        【解决方案4】:

        您可以对代码进行的大多数基本修改只是更改这些行集

        for i in animals:
            for j in i:
                print(j)
        

        其他人的相同概念只是对您已有的内容进行了最小的调整。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-22
          • 2015-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多