2012-09-13 14 views
7

Sono abbastanza nuovo alla programmazione e non capisco molti concetti. Qualcuno può spiegarmi la sintassi della riga 2 e come funziona? Non c'è bisogno di indentazione? E anche da dove posso imparare tutto questo?Sintassi complessa- Python

string = #extremely large number 

num = [int(c) for c in string if not c.isspace()] 
+2

Questa è una lista di comprensione. Sì, puoi leggere su di loro su python.org. –

+3

Questo è chiamato un elenco di comprensione. Un'introduzione: http://carlgroner.me/Python/2011/11/09/An-Introduction-to-List-Comprehensions-in-Python.html –

+0

In sostanza, molti programmatori Python si sono trovati a utilizzare un insieme simile di dichiarazioni più e più volte, e ha deciso che, in quanto programmatori, possono semplificare questo compito di routine. – Hannele

risposta

14

Questo è un list comprehension, una sorta di scorciatoia per la creazione di un nuovo elenco. E 'funzionalmente equivalente a:

num = [] 
for c in string: 
    if not c.isspace(): 
     num.append(int(c)) 
4

Significa esattamente quello che dice.

num =  [   int(      c) 

"num" shall be a list of: the int created from each c 

for c       in string 

where c takes on each value found in string 

if  not      c .isspace() ] 

such that it is not the case that c is a space (end of list description) 
1

Giusto per ampliare la risposta di mgilson come se sei abbastanza nuovo per la programmazione, che può anche essere un po 'ottuso. Da quando ho iniziato a imparare Python qualche mese fa, ecco le mie annotazioni.

string = 'aVeryLargeNumber' 
num = [int(c) for c in string if not c.isspace()] #list comprehension 

"""Breakdown of a list comprehension into it's parts.""" 
num = [] #creates an empty list 
for c in string: #This threw me for a loop when I first started learning 
    #as everytime I ran into the 'for something in somethingelse': 
    #the c was always something else. The c is just a place holder 
    #for a smaller unit in the string (in this example). 
    #For instance we could also write it as: 
    #for number in '1234567890':, which is also equivalent to 
    #for x in '1234567890': or 
    #for whatever in '1234567890' 
      #Typically you want to use something descriptive. 
    #Also, string, does not have to be just a string. It can be anything 
    #so long as you can iterate (go through it) one item at a time 
    #such as a list, tuple, dictionary. 

if not c.isspace(): #in this example it means if c is not a whitespace character 
     #which is a space, line feed, carriage return, form feed, 
       #horizontal tab, vertical tab. 

num.append(int(c)) #This converts the string representation of a number to an actual 
     #number(technically an integer), and appends it to a list. 

'1234567890' # our string in this example 
num = [] 
    for c in '1234567890': 
     if not c.isspace(): 
      num.append(int(c)) 

La prima iterazione del ciclo sarà simile:

num = [] #our list, empty for now 
    for '1' in '1234567890': 
     if not '1'.isspace(): 
      num.append(int('1')) 

nota la '' attorno al 1. nulla tra '' o "" significa che questo elemento è una stringa. Anche se sembra un numero, per quanto riguarda Python non lo è. Un modo semplice per verificare che sia di digitare 1 + 2 nell'interprete e confrontare il risultato con '1' + '2'. Vedere una differenza? Con i numeri li aggiunge come ti aspetteresti. Con le stringhe si unisce a loro.

Al secondo passaggio!

num = [1] #our list, now with a one appended! 
    for '2' in '1234567890': 
     if not '2'.isspace(): 
      num.append(int('2')) 

E così continuerà fino a quando non esaurisce i caratteri nella stringa, o produce un errore. Cosa succederebbe se la stringa fosse "1234567890.12345"? Possiamo tranquillamente dire che "." non è un carattere di spazio bianco. Così, quando ci mettiamo a int ('') Python sta per gettare un errore:

Traceback (most recent call last): 
    File "<string>", line 1, in <fragment> 
builtins.ValueError: invalid literal for int() with base 10: '.' 

quanto riguarda le risorse per l'apprendimento Python, ci sono un sacco di tutorial gratuiti quali:

http://www.learnpython.org

http://learnpythonthehardway.org/book

http://openbookproject.net/thinkcs/python/english3e

http://getpython3.com/diveintopython3

Se si desidera acquistare un libro per l'apprendimento, quindi: http://www.amazon.com/Learning-Python-Powerful-Object-Oriented-Programming/dp/0596158068 è il mio preferito. Non sono sicuro del motivo per cui le valutazioni siano basse, ma penso che l'autore faccia un ottimo lavoro.

Buona fortuna!

0

Questi esempi dello PEP sono un buon punto di partenza. Se non hai familiarità con range e % devi fare un passo indietro e imparare di più sulle basi.

>>> print [i for i in range(10)] 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

>>> print [i for i in range(20) if i%2 == 0] 
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18] 

>>> nums = [1,2,3,4] 
>>> fruit = ["Apples", "Peaches", "Pears", "Bananas"] 
>>> print [(i,f) for i in nums for f in fruit] 
[(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'), 
(2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'), 
(3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'), 
(4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')] 
>>> print [(i,f) for i in nums for f in fruit if f[0] == "P"] 
[(1, 'Peaches'), (1, 'Pears'), 
(2, 'Peaches'), (2, 'Pears'), 
(3, 'Peaches'), (3, 'Pears'), 
(4, 'Peaches'), (4, 'Pears')] 
>>> print [(i,f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1] 
[(1, 'Peaches'), (1, 'Pears'), (3, 'Peaches'), (3, 'Pears')] 
>>> print [i for i in zip(nums,fruit) if i[0]%2==0]