列表理解python

2 lisp python list-comprehension

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

(loop for x = input then (if (evenp x)
                             (/ x 2)
                             (+1 (* 3 x)))
      collect x
      until (= x 1))
Run Code Online (Sandbox Code Playgroud)

Kiv*_*Kiv 10

列表推导用于获取现有序列并对其执行某些功能和/或过滤,从而产生新列表.因此,在这种情况下,列表理解是不合适的,因为您没有起始序列.while循环的示例:

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


Mik*_*per 9

我相信你正在编写冰雹序列,虽然我可能错了,因为我不熟悉Lisp.

据我所知,你只能在列表理解中做到这一点,因为每个元素都取决于最后一个元素.

我将如何做到这一点

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) ]
Run Code Online (Sandbox Code Playgroud)

当然,无论您的输入是什么,输入都会保留.

我的hailstone功能可能更简洁.我的目标是清晰.