Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python空元组列表_Python_List_While Loop_Tuples_Is Empty - Fatal编程技术网

Python空元组列表

Python空元组列表,python,list,while-loop,tuples,is-empty,Python,List,While Loop,Tuples,Is Empty,作业中的一个问题要求我编写一个函数,使用while循环迭代输入元组列表,然后计算达到特定里程碑所需的天数。我已经完成了部分,但是如果输入列表为空,我还需要使我的函数返回None。问题是我的代码中只允许有一个return语句,这就是我被卡住的地方。如何编辑代码以添加此功能 def days_to_reach_n_steps(step_records, n): """DOCSTRING""" total_steps = 0 counter = 0 while total_steps

作业中的一个问题要求我编写一个函数,使用while循环迭代输入元组列表,然后计算达到特定里程碑所需的天数。我已经完成了部分,但是如果输入列表为空,我还需要使我的函数返回
None
。问题是我的代码中只允许有一个return语句,这就是我被卡住的地方。如何编辑代码以添加此功能

def days_to_reach_n_steps(step_records, n):
  """DOCSTRING"""
  total_steps = 0
  counter = 0
  while total_steps < n:
      total_steps = total_steps + step_records[counter][1]
      counter = counter + 1
  return(counter) here
def天数到达步骤(步骤记录,n):
“文档字符串”
总步数=0
计数器=0
当总步数
试试这个

def days_to_reach_n_steps(step_records, n):
  """DOCSTRING"""
  total_steps = 0
  counter = 0
  if len(step_records)>0:
      while total_steps < n:
          if(counter <len(step_records):
              total_steps = total_steps + step_records[counter][1]
              counter = counter + 1
          else:
              counter = "Your Message"
  return(counter if counter!=0 else None) 
def天数到达步骤(步骤记录,n):
“文档字符串”
总步数=0
计数器=0
如果len(步骤记录)>0:
当总步数if(counter抱歉,我忘了提及我已经尝试过了,但出现了一个错误,显示“builtins.IndexError:列表索引超出范围”。我想这个错误可能是由我的
total_steps=total_steps+step_records[counter][1]引起的
。也许此行不允许输入空列表?还有其他想法吗?为什么不使用for循环,这是因为您正在访问列表中的一个元素,当列表为空时,使用for循环会更容易些,但是在循环时,分配的这一部分是打开的,因此很遗憾,我被迫排除for循环。请尝试检查在访问列表元素之前在列表中创建索引。这是通过if-else循环实现的。我假设您的意思是
if len(step_records)>0
(执行while循环),但是如果len(step_records)==0,我如何告诉函数在不使用第二个返回语句的情况下输出
None