【问题标题】:Basic while loop returning a numbered list返回编号列表的基本 while 循环
【发布时间】:2021-06-14 07:51:26
【问题描述】:

我对编程非常陌生,并且在我的一个课程测验中被困在这个基本问题上:编写一个函数numbered_list(items),它将列表items中的项目的编号(从1开始)列表打印为在下面的测试用例中显示。我们不允许使用“for”语句,它必须有一个while 语句!我尝试过使用枚举,但我认为我的课程要求更长的格式

我得到的最接近的是下面的代码,但仍然无法得到我想要的答案。

def numbered_list(items):
"""Prints a numbered list of items starting from 1"""
i = 0 
while i <len(items):
    print(items[i])
    i += 1
print (items)

使用以下测试:

todos = ["Watch lecture videos", "Complete quiz", "Practise"]
numbered_list(todos)

它应该导致:

1 Watch lecture videos
2 Complete quiz
3 Practise

任何帮助或答案将不胜感激!

【问题讨论】:

  • 您只在items 中的i 位置打印项目。打印索引和项目!您已经在i 中拥有索引,在items[i] 中拥有项目。
  • 您是否考虑过使用the enumerate function 为您计数,而不是自己跟踪i?
  • @CharlesDuffy 不允许使用该功能!
  • @crcvd 嘿,我试过 print (items[i]) 但它说列表超出范围
  • fwiw,在这里使用 while 循环不是惯用的 Python。相反,您想要一个 for 循环或更可能是一个列表理解。此外,使用格式字符串打印使您的代码更具可读性:print(f"{idx}: {item}") 当 idx 和 item 分别定义为列表编号和该位置的项目时。

标签: python list function while-loop


【解决方案1】:

代码必须在函数定义后缩进 在while 循环之后,它必须是这样的:

def numbered_list(items):
    """Prints a numbered list of items starting from 1"""
    i = 0 

    while i <len(items):
        print(items[i])
        
        
        i += 1
        
todos = ["Watch lecture videos", "Complete quiz", "Practise"]
numbered_list(todos)  

【讨论】:

    【解决方案2】:

    enumerate() 返回一对索引和值。

    todos = ["Watch lecture videos", "Complete quiz", "Practise"]
    
    
    def numbered_list(items):
        for idx, item in enumerate(items, start=1):
            print(idx, item)
    
    numbered_list(todos)
    

    【讨论】:

      【解决方案3】:

      这是您的代码已更改为完全符合您的要求:

      def numbered_list(items):
          """Prints a numbered list of items starting from 1"""
          i = 0 
          while i <len(items):
              print(i+1,items[i])
              i += 1
          print (items)
      
      todos = ["Watch lecture videos", "Complete quiz", "Practise"]
      numbered_list(todos)
      

      我改变的只是打印语句,在列表项之前打印 i+1 :

      print(i+1,items[i])
      

      此代码输出:

      1 Watch lecture videos
      2 Complete quiz
      3 Practise
      

      【讨论】:

      • 谢谢!!现在看到它的欢呼声就更直接了
      • @coschal 如果这解决了您的问题,请将其标记为解决方案并感谢您:)
      猜你喜欢
      • 2019-03-31
      • 2015-11-17
      • 2017-11-09
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      相关资源
      最近更新 更多