簡體   English   中英

Python使用while循環處理元組列表

[英]Python Manipulating a list of tuples using a while loop

我正在嘗試編寫一個python函數,該函數使用while循環來遍歷元組的輸入列表,該元組包含日期和在每個日期上執行的步數。 我函數的兩個輸入是列表和一些必需的步驟。 該功能需要遍歷該列表並計算達到所需步驟數所花費的天數。 到目前為止,以下是我的代碼,該代碼可用於初始部分,但是我還需要對其進行添加,以便如果在元組的輸入列表中未達到所需的步數,則該函數將返回“無”。 另一件事是我只能有一個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)

我正在測試功能的示例,此特定示例應返回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)

在我看來,最簡單的解決方案是此處的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語句,但仍設法為37 return None 這是因為隱式不返回任何內容的函數將返回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 <(python while.py) <(python code.py)完全退出)。

為了使其適應於for循環的第一次迭代,請刪除對step_records的重新分配,並返回counter + 1

請注意,這並不是while循環的真正好應用-也許目的是通過while循環進行練習,但我真的不贊成強制使用丑陋的代碼-Python已經有了用於遍歷列表和保留索引的簡單習語。 參見Python之禪

到達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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM