单语句斐波那契
可能的重复:
斐波那契数列,在 Python 3 中带有一行代码?
这可能是很简单的事情,但我对 Python 很陌生。我想出了这个单一的斐波那契陈述。
[fibs.append(fibs[-2]+fibs[-1]) for i in xrange(1000)]
不过,这并不是一个单一的声明。在触发此语句(即 fibs = [0, 1]
)之前,我需要初始化列表 fibs
。
现在,我有两个问题,
我们如何摆脱这个列表初始化语句,
fibs = [0, 1]
,以使其成为真正的单个语句?原始语句打印
None
n 次;其中 n 是在xrange()
中传递的数字。有什么办法可以完全避免这种情况吗?或者如果该语句可以打印该系列,那就更好了。那么我们就不需要显式地打印fibs
。
[已编辑]
或者我们是否有任何替代 list.append()
的方法来返回它附加到的 list
?
Possible Duplicate:
Fibonacci numbers, with an one-liner in Python 3?
It may be very easy thing, but I am very new to Python. I came up with this single statement Fibonacci.
[fibs.append(fibs[-2]+fibs[-1]) for i in xrange(1000)]
Not really single statement, though. I need to initialise the list, fibs
, before firing this statement i.e. fibs = [0, 1]
.
Now, I have 2 questions,
How can we get rid of this list initialisation statement,
fibs = [0, 1]
, in order to make it really single statement?Original statement prints
None
n times; where n is the number passed inxrange()
. Is there any way to avoid that altogether? Or better if the statement can print the series, instead. Then we don't need to printfibs
explicitly.
[Edited]
Or do we have any alternative to list.append()
which returns the list
it appends to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可行的:
这是比奈公式的一个实现。
http://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio
This works:
This is an implementation of Binet's Formula.
http://en.wikipedia.org/wiki/Fibonacci_number#Relation_to_the_golden_ratio
嗯,这根本不符合习惯用法。您在这里所做的是使用列表理解作为
for
循环的快捷方式。尽管 Python 的推导式可能会产生副作用,但 Python 并不是为此而设计的。我想不出有什么办法可以让它发挥作用,但这可能是一件好事。对于您的 2),请考虑您实际上正在创建一个列表,其中的项目是调用
fibs.append(fibs[-2]+fibs[-1])
的返回值,这是一种副作用方法从而返回None
。有关详细信息,请参阅文档。不错的尝试,但这不是 Python 的用途:)
Well, this is not idiomatic at all. What you are doing here is using a list comprehension as a shortcut for a
for
loop. Though Python's comprehensions can have side effects, Python is not designed for this. I can't think of no way to get this to work and it is probably a good thing.For your 2), consider that you are actually creating a list which items are return values of the call
fibs.append(fibs[-2]+fibs[-1])
which is a side effect method and thus returnNone
. See the doc for details.Nice try but this is not what Python is for :)
试试这个
try this out