列表理解python

2024-04-20 13:44:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,以下常用Lisp代码的等效列表理解是什么:

(loop for x = input then (if (evenp x)
                             (/ x 2)
                             (+1 (* 3 x)))
      collect x
      until (= x 1))

Tags: 代码loop列表forinputifuntilcollect
3条回答

列表理解用于获取现有序列并对其执行某些功能和/或筛选,从而生成新的列表。因此,在这种情况下,列表理解是不合适的,因为您没有一个开始序列。带有while循环的示例:

numbers = []
x=input()
while x != 1:
  numbers.append(x)
  if x % 2 == 0: x /= 2
  else: x = 3 * x + 1

Python没有内置这种控制结构,但是您可以将其归纳为这样的函数:

def unfold(evolve, initial, until):
    state = initial
    yield state
    while not until(state):
        state = evolve(state)
        yield state

在此之后,您的表达式可以写成:

def is_even(n): return not n % 2
unfold(lambda x: x/2 if is_even(x) else 3*x + 1,
       initial=input, until=lambda x: x == 1)

但是python的方法是使用一个生成器函数:

def produce(x):
    yield x
    while x != 1:
        x = x / 2 if is_even(x) else 3*x + 1
        yield x

我相信你在写冰雹序列,虽然我可能是错的,因为我不流利的口齿不清。

据我所知,不能只在列表理解中这样做,因为每个元素都依赖于最后一个元素。

我会怎么做

def hailstone(n):
    yield n
    while n!=1
        if n%2 == 0: # even
            n = n / 2
        else: # odd
            n = 3 * n + 1
        yield n

list = [ x for x in hailstone(input) ]

当然,输入可以保存任何输入。

我的冰雹函数可能更简洁。我的目标是明确。

相关问题 更多 >