問題陳述:
我需要收集重複執行的計算的結果對於x 的多個值,然後使用它們。
使用明確循環:
ys = [] for x in [1, 3, 5]: ys.append(x + 1) ys = {} x = 19 while x != 1: y = next_collatz(x) ys[x] = y x = y
使用理解式或生成器表達式:
列表理解:
xs = [1, 3, 5] ys = [x + 1 for x in xs]
字典理解:
ys = {x: x + 1 for x in xs}
使用map:
將函數對應到序列,並將結果轉換為清單:
def calc_y(an_x): return an_x + 1 xs = [1, 3, 5] ys = list(map(calc_y, xs))
具體範例:
收集固定結果序列:
def make_list_with_inline_code_and_for(): ys = [] for x in [1, 3, 5]: ys.append(x + 1) return ys def make_dict_with_function_and_while(): x = 19 ys = {} while x != 1: y = next_collatz(x) ys[x] = y # associate each key with the next number in the Collatz sequence. x = y # continue calculating the sequence. return ys
管理循環期間更改的資料:
使用生成器表達式:
def collatz_from_19(): def generate_collatz(): nonlocal x yield x while x != 1: x = next_collatz(x) yield x x = 19 return generate_collatz()
使用地圖:
def collatz_from_19_with_map(): def next_collatz2(value): nonlocal x x = value return next_collatz(x) x = 19 return map(next_collatz2, range(1))
以上是如何有效率地收集Python重複計算的結果?的詳細內容。更多資訊請關注PHP中文網其他相關文章!