2014-01-30 30 views
0
def pop(n): 
    result,counter = 0,0 
    while counter<=n: 
     result=(2**counter) 
     counter=counter+1 
    return result 

example: 
>>>pop(4) 
16 

如何返回所有結果?像:Python:如何在循環中返回所有結果?

1 
2 
4 
8 
16 
+0

流行是一個內置的功能,你應該避免使用它爲自己的函數 – Kraay89

+0

@ Kraay89名稱:不,不是。 – geoffspear

+0

'mylist = [1,2,3,4]','mylist.pop()'會起作用嗎?你在做什麼?我用錯了詞嗎?因爲它是一個有效的python函數...:S – Kraay89

回答

4

您可以將結果保存在一個列表:

def pop(n): 
    result,counter = [],0 
    while counter<=n: 
     result.append(2**counter) 
     counter=counter+1 
    return result 

現在的結果將是所有權力清單。

或者,如果你做一個list(pop(4))你可以創建一個發電機來yield多個結果

def pop(n): 
    result,counter = 0,0 
    while counter<=n: 
     yield 2**counter 
     counter=counter+1 

現在,那麼你會得到所有結果

+4

你可能是指'yield'而不是'yeild' :) – gioi

1

的Python的方式的名單將是這樣的:

def pop(n): return [2**x for x in range(n)] 
+0

更多關於列表解析的信息在這裏:http://docs.python.org/2/tutorial/ datastructures.html#列表內涵。你的例子就在那裏... – Peter