2011-06-11 54 views
0

我正在研究Learn Python The Hard Way PDF。在第82頁,我遇到了這個問題。'範圍'功能是否可以分配給列表?

  • 你能避免完全在第23行的for-loop,只是直接指定範圍(0,6)到元素?

給予代碼:

# we can also build lists, first start with an empty one 
elements = [] 

# then use the range function to do 0 to 20 counts 
for i in range(0, 6): 
    print "Adding %d to the list." % i # line 23 
    # append is a function that lists understand 
    elements.append(i) 

# now we can print them out too 
for i in elements: 
    print "Element was: %d" % i 

看來這是不可能的,除非我使用地圖功能?我對麼?

回答

10

在python 2.x中,range返回一個列表。在3.x中,它返回一個可迭代的範圍對象。您始終可以使用list(range(...))獲取列表。

然而,for x in y不需要y是一個列表,只是一個迭代(如xrange(2.X只),rangeliststr,...)

2

的提示很可能意味着建議,你可以簡單地使用

elements = range(6) 

具有相同的結果。

0

elements = range(0,6)

這是一個隱式列表。

+0

謝謝(大家)。我覺得太困難了。 – 2011-06-11 19:20:44

+7

@Bas van der Zon - 這個答案只適用於Python 2.x,而不是3. – Omnifarious 2011-06-11 19:24:06

4

但你也可以做的相當複雜的任務也是如此。

elements = [0,1,2,3,4,5,6,7,8,9,10] 

elements[3:5] = range(10,12) # replace indexes 3 and 4 with 10 and 11. 

elements[3:7:2] = range(100,201,100) replace indexes 3 and 5 with 100 and 200 

elements[:] = range(4) # replace entire list with [0,1,2,3] 

[start,end,by]符號稱爲切片。開始是從(包括,默認爲0)開始的索引。 End是要結束的索引(獨佔,默認是len(list))。由是如何從指數移動到下一個(默認爲1)

+0

這些都不能在Python 3中工作。 – Omnifarious 2011-06-11 19:22:56

+0

真的嗎?這很糟糕。是否有新的語法/功能來彌補損失? – Dunes 2011-06-11 20:19:15

+0

不是真的,除了第三條語句之外的所有內容都在Python 3中工作。僅僅第三條語句不起作用,因爲200需要用201替換(或者只有一個元素在範圍中)。 – 2011-06-11 21:32:30

0
elements = range(0,5) 
elements.extend(range(5, 10)) 
#elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

More on extend