问题陈述:
我需要收集重复执行的计算的结果对于 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中文网其他相关文章!