2010-08-11 55 views
2

我通過一些代碼示例工作我的方式,我偶然發現了這一點:Python的+和*運營商

endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] 
+ ['st'] 

我明白了4起直到20號,他們在「日」結束,我可以看到我們將17個項目添加到列表中,並且我知道'17 *''th']將17次添加到列表中,但是,我不明白這是如何工作的。

你可以對此有所瞭解嗎?

+0

注意,這不是在所有區域設置適當的;) – 2010-08-11 16:42:06

回答

5

17 * ['th']生成['th', 'th', ..., 'th'](17項目)。

另外值得注意的2種行爲:

  • ,由於內容'th'是不可變的,這是唯一真正有用的(當然,除非你永遠不打算修改結束列表)。
  • 列表對象['th']只創建一次,但是它通過迭代17次原始副本進行擴展,將每個條目附加到最終的['th', ...]列表中。這又通過+運營商與周圍的結局合併。

我通常不會擺脫我的光。大約每6個月一次。如果你看到它躺着不要告訴任何人它是我的。

0

考慮 二十 二十一 第二十二 第二十三個 ... 三十 第三十一個

抑或是別的東西,你不明白呢?

+0

CrazyJuggler,釘在了我的不理解。 *運算符正在創建一個全新的列表,然後將其添加到之前的列表中。 – 2010-08-11 15:50:50

1

代碼17 * ['th']的部分創建了17項全部'th'和+運算符連接列表一起的清單,讓['st', 'nd', 'rd'] + 17 * ['th']將成爲['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th']

2

當乘以一個列表,你」重新創建一個包含多次列表元素的新列表。在這種情況下,17 * ['th']創建一個包含十七個字符串'th'的列表。將列表一起添加時,您將創建一個包含所有操作數元素的新列表。

>>> a = [1, 2] 
>>> a * 2 
[1, 2, 1, 2] 

>>> a = ['th'] 
>>> b = ['st'] 
>>> 3 * a + b 
['th', 'th', 'th', 'st'] 
1

這使得下面的列表:

endings = [ "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th" ] 

所以,如果你想要寫 「21」,做

"{0}{1}".format(21, endings[ 20 ]) 

注意,列表是關閉的一個,因爲endings[0]是第一個元素。

+0

'ordinal = lambda x:str(x)+ endings [x - 1]',對於0 2010-08-11 16:23:11

0

此外,您可以覆蓋自己的對象的運算符,例如

#!/usr/bin/env python 
# encoding: utf-8 

class SomeClass(object): 
    def __init__(self, v): 
     self.value = v 

    def __add__(self, b): 
     return self.value + b.value 

def main(): 
    a = SomeClass(1) 
    b = SomeClass(2) 
    print a + b 


if __name__ == '__main__': 
    main() 

看到http://docs.python.org/library/operator.html更多細節