【问题标题】:How do I implement the counter from this for cycle to a list by comprehension?如何通过理解实现从这个循环到列表的计数器?
【发布时间】:2019-03-18 19:00:33
【问题描述】:

这段代码怎么写

def Serie_a(n):
    Serie_a = []
    m=0
    for i in [1..n]:
        m = m + 1/i
        Serie_a.append(m)
    print Serie_a

以理解列表的形式?

【问题讨论】:

  • 如果你只想要最后一个元素(你可能不想要,只是猜测),你可以做result = reduce(lambda x, y: x + 1/float(y), range(1, n+1))

标签: python list list-comprehension counter


【解决方案1】:

目前,您无法编写像 for 循环一样容易阅读的列表理解。请改用itertools.accumulate

>>> list(accumulate(range(1,11), lambda acc, x: acc + 1/x))
[1, 1.5, 1.8333333333333333, 2.083333333333333, 2.283333333333333, 2.4499999999999997, 2.5928571428571425, 2.7178571428571425, 2.8289682539682537, 2.9289682539682538]

在 Python 3.8 中,assignment expressions 将允许您编写

% ./python.exe
Python 3.8.0a2 (tags/v3.8.0a2:23f4589b4b, Mar 18 2019, 15:16:44)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> m = 0
>>> [m := m + 1/x for x in range(1,11)]
[1.0, 1.5, 1.8333333333333333, 2.083333333333333, 2.283333333333333, 2.4499999999999997, 2.5928571428571425, 2.7178571428571425, 2.8289682539682537, 2.9289682539682538]

请注意,m 需要先初始化,然后才能用于列表解析。

【讨论】:

    猜你喜欢
    • 2022-06-14
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 2019-12-08
    • 2013-10-11
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多