【问题标题】:Python Manipulating a list of tuples using a while loopPython使用while循环操作元组列表
【发布时间】:2018-02-25 23:35:50
【问题描述】:

我正在尝试编写一个 python 函数,该函数使用 while 循环来遍历包含日期和在每个日期行走的步数的元组的输入列表。我的函数的两个输入是列表和一些必需的步骤。该函数需要遍历列表并计算达到所需步数所需的天数。下面是我到目前为止的代码,它适用于初始部分,但是我还需要添加它,以便如果在元组的输入列表中未达到所需的步骤数,则该函数返回“无”。另一件事是我只能有一个返回语句,因为问题说明了,这也是我坚持下去的部分原因。

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)

我正在测试我的函数的示例,这个特定示例应该返回 None,因为列表中的步骤从未达到或超过 50。

step_records = [('2010-01-01',3), ('2010-01-02',2), ('2010-01-03',1)] days = days_to_reach_n_steps(step_records, 50) print(days)

【问题讨论】:

  • 你能提供一个step_records 的样例吗(如果你只使用一个部分,为什么它是一个元组列表?),以及你的预期输出是什么与你是什么到目前为止?
  • 用我调用函数的示例编辑了我的问题。在修改函数以返回到达n 的日期之后,我将使用step_records 的日期部分,但是我认为最好不要考虑这部分,因为我认为我应该专注于首先弄清楚初始部分。
  • 如果n 为0,你会返回多少天/日期?
  • 不会撒谎,我没想到。我想 0 或 None 的输出也适用于这种情况。

标签: python list while-loop tuples


【解决方案1】:

在我看来,最简单的解决方案是这里的for 循环,因为从根本上说您想要的是迭代。您还可以使用enumerate 跟踪当天:

sample_steps = [("2010-01-1", 1),
                ("2010-01-2", 3),
                ("2010-01-3", 5),
                ("2010-01-4", 7),
                ("2010-01-5", 9),
                ("2010-01-6", 11)]

def days_to_reach_n_steps(step_records, n):
    total_steps = 0
    for counter, (date, steps) in enumerate(step_records, 1):
        total_steps += steps
        if total_steps >= n:
            return counter, date

我选择了奇数作为步骤的顺序,因为它们的累积和是平方(更容易用肉眼检查):

for boundary in range(1, 7):
    for steps in range(boundary ** 2 - 1, boundary ** 2 + 2):
        result = days_to_reach_n_steps(sample_steps, steps)
        if result:
            days, date = result
            print("{} steps in {} days (arrived at {})".format(steps, days, date))
        else:
            print("{} was unreached".format(steps))

这将返回:

0 steps in 1 days (arrived at 2010-01-1)
1 steps in 1 days (arrived at 2010-01-1)
2 steps in 2 days (arrived at 2010-01-2)
3 steps in 2 days (arrived at 2010-01-2)
4 steps in 2 days (arrived at 2010-01-2)
5 steps in 3 days (arrived at 2010-01-3)
8 steps in 3 days (arrived at 2010-01-3)
9 steps in 3 days (arrived at 2010-01-3)
10 steps in 4 days (arrived at 2010-01-4)
15 steps in 4 days (arrived at 2010-01-4)
16 steps in 4 days (arrived at 2010-01-4)
17 steps in 5 days (arrived at 2010-01-5)
24 steps in 5 days (arrived at 2010-01-5)
25 steps in 5 days (arrived at 2010-01-5)
26 steps in 6 days (arrived at 2010-01-6)
35 steps in 6 days (arrived at 2010-01-6)
36 steps in 6 days (arrived at 2010-01-6)
37 was unreached

请注意,days_to_reach_n_steps 只有一个return 语句,但仍设法将return None 用于37。这是因为一个不返回任何内容的函数隐含地返回None。但是,这与您对 0 的规范不太匹配。如果您希望 0 异常,我建议您这样做:

for counter, (date, steps) in enumerate([("start", 0)] + step_records):

答案的第一行会变成

0 steps in 0 days (arrived at start)

这维护了算法的其余部分,因此您无需编写边缘情况。

如果它必须是一个while循环,你可以稍微滑稽地把for循环改写成这样:

def days_to_reach_n_steps(step_records, n):
    total_steps = 0
    counter = 0
    step_records = [("start", 0)] + step_records
    while counter < len(step_records):
        date, steps = step_records[counter]
        total_steps += steps
        if total_steps >= n:
            return counter, date
        counter += 1

这与 for 循环方法的第二次迭代完全相同($ diff &lt;(python while.py) &lt;(python code.py) 干净地退出)。

要使其类似于 for 循环的第一次迭代,请删除对 step_records 的重新分配并返回 counter + 1

请注意,这并不是一个很好的 while 循环应用程序——也许是为了练习使用 while 循环,但我真的不赞成强制使用丑陋的代码——Python 已经有简单的习惯用法来迭代列表和保持索引。见the Zen of Python

【讨论】:

  • 是的,我之前用 for 循环解决了这个问题,但问题是它不允许 for 循环,必须使用 while 循环。使用 while 循环还有其他可能的解决方案吗?
  • 你是个传奇。赞成并标记为答案。感谢您的宝贵时间!
【解决方案2】:

IndexError 退出并在未到达时将c 设置为None

def daystoreach(steprecords, n):
total = 0
x = 0
while total < n:
    try:
        total += sr[x][1]
        x += 1
    except IndexError:
        break
if total < n:
    x = None
return x

【讨论】:

  • 我真的建议使用比这更具表现力的变量名称 - 如果我没有使用您的缩写扩展,我不知道 dtrns 是什么。
  • 做了(是的,很晚了)
猜你喜欢
  • 1970-01-01
  • 2015-09-13
  • 2021-11-13
  • 2018-10-25
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
相关资源
最近更新 更多