7

我对编程很陌生,很多概念都不懂。有人可以向我解释第 2 行的语法及其工作原理吗?不需要缩进吗?而且,我可以从哪里学到这一切?

string = #extremely large number

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

4 回答 4

14

那是一个列表推导,一种创建新列表的简写。它在功能上等同于:

num = []
for c in string:
    if not c.isspace():
       num.append(int(c))
于 2012-09-13T19:05:05.327 回答
4

它的意思正是它所说的。

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)
于 2012-09-13T21:03:13.663 回答
1

只是为了扩展 mgilson 的答案,就好像您对编程很陌生,这也可能有点迟钝。自从几个月前我开始学习 python 以来,这是我的注释。

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))

通过循环的第一次迭代看起来像:

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

注意 1 周围的 ' '。' ' 或 " " 之间的任何内容都表示该项目是一个字符串。尽管它看起来像一个数字,但就 Python 而言,它不是。一个简单的验证方法是在解释器中输入 1 + 2 并将结果与​​ '1' + '2' 进行比较。看出区别了吗?使用数字,它可以按照您的预期将它们加在一起。使用字符串将它们连接在一起。

进入第二关!

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

所以它会一直持续下去,直到字符串中的字符用完,或者产生错误。如果字符串是 '1234567890.12345' 会发生什么?我们可以放心地说'。不是空格字符。所以当我们深入到 int('.') Python 会抛出一个错误:

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

至于学习 Python 的资源,有很多免费教程,例如:

http://www.learnpython.org

http://learnpythonthehardway.org/book

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

http://getpython3.com/diveintopython3

如果您想购买一本书进行学习,那么:http ://www.amazon.com/Learning-Python-Powerful-Object-Oriented-Programming/dp/0596158068是我的最爱。不知道为什么收视率很低,但我认为作者做得很好。

祝你好运!

于 2012-09-13T21:26:11.873 回答
0

PEP中的这些示例是一个很好的起点。如果你不熟悉,range%需要退后一步,了解更多关于基础的信息。

>>> 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]
于 2012-09-13T21:40:42.393 回答