2014-01-30 53 views

回答

7

的代碼,你給我的線,基本上是做三件事情:

  1. 它採用串line和使用str.split拆分它+的。這將返回字符串的列表:

    >>> line = 'a+b+c+d' 
    >>> line.split('+') 
    ['a', 'b', 'c', 'd'] 
    >>> 
    
  2. [-1]然後索引,列出在-1位置。這樣做將返回的最後一個項目:

    >>> ['a', 'b', 'c', 'd'][-1] 
    'd' 
    >>> 
    
  3. 它需要這個項目,並將其分配作爲變量name的值。

下面是上面提到的概念更完整的演示:

>>> line = 'a+b+c+d' 
>>> line.split('+') 
['a', 'b', 'c', 'd'] 
>>> lst = line.split('+') 
>>> lst[-1] 
'd' 
>>> lst[0] 
'a' 
>>> lst[1] 
'b' 
>>> lst[2] 
'c' 
>>> lst[3] 
'd' 
>>> 
1

str.split返回一個列表:

>>> '1+2+3'.split('+') 
['1', '2', '3'] 

list[-1]產生了最後一個項目(負指數從-1開始)

>>> '1+2+3'.split('+')[-1] 
'3' 
>>> '1+2+3'.split('+')[0] # the first item (Python index starts from 0) 
'1' 
>>> '1+2+3'.split('+')[1] 
'2' 

請參閱Lists - Python tutorial(包含索引,切片)。

0

Split將創建列表,然後從你得到使用Python中[-1]

1

負指標的最後一個元素是語法糖在訪問元素順序顛倒,從右到左,在-1開始。所以-1是最後一項,-2是倒數第二項,依此類推 - 第一項應該是lst[-len(lst)]。例如:

lst = [1, 2, 3] 
lst[-1] 
=> 3 
lst[-2] 
=> 2 
lst[-3] 
=> 1 
相關問題