2009-07-01 13 views
7
f = lambda x : 2*x 
g = lambda x : x ** 2 
h = lambda x : x ** x 
funcTriple = (f, g, h) 
myZip = (zip (funcTriple, (1, 3, 5))) 
k = lambda pair : pair[0](pair[1]) 

# Why do Output # 1 (2, 9, 3125) and Output # 2 ([ ]) differ? 

print ("\n\nOutput # 1: for pair in myZip: k(pair) ...") 
for pair in myZip : 
    print (k(pair)) 

print ("\n\nOutput # 2: [ k(pair) for pair in myZip ] ...") 
print ([ k(pair) for pair in myZip ]) 

# script output is ... 
# Output # 1: for pair in myZip: k(pair) ... 
# 2 
# 9 
# 3125 
# 
# Output # 2: [ k(pair) for pair in myZip ] ... 
# [] 

risposta

18

Funziona perfettamente in Python 2.6 ma non riesce in Python 3.0 poiché zip restituisce un oggetto in stile generatore e il primo ciclo lo esaurisce. Fate una lista, invece:

myZip = list(zip (funcTriple, (1, 3, 5))) 

e funziona in Python 3.0

+0

funziona bene per me in IronPython troppo. –

+0

Sì, trovo che funzioni perfettamente con Python 2.5: Output # 2 è [2, 9, 3125]. Tuttavia, quando utilizzo Python 3.0, restituisce l'output "erroneo" e Output # 2 è []. –

+0

Grazie mille! Leggerò oggetti "in stile generatore" e il loro "esaurimento". –

Problemi correlati