簡體   English   中英

為什么我的清單不遍歷每個清單?

[英]Why won't my list iterate over each one?

當前正在通過教程“ Python的艱難方法”進行工作。

我正在學習列表和循環(ex32)。

練習結束時,Zed(教程作者)告訴我們,我已經完成了游戲。

# we can also build lists, first start with an empty one
elements = []
elements.append(range(0,6))

# then use the range function to do 0 to 5 counts
for element in elements:
    print "Adding %s to elements" % element


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

這樣產生的輸出如下:

Adding [0, 1, 2, 3, 4, 5] to elements
Element was: [0, 1, 2, 3, 4, 5]

我曾期望看到這樣的事情:

Adding 0 to elements
Adding 1 to elements
Adding 2 to elements
Adding 3 to elements
Adding 4 to elements
Adding 5 to elements
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

但是相反,Python希望一次打印出我的腳本,而不是將每個列表組件的連接字符串打印出來。

我知道我可以更改腳本以准確反映作者的腳本

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

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print "Adding %d to the list." % i
    # 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

但我只想知道為什么我的作品無法按預期工作?

您正在將列表追加到列表! 您只想創建列表!

您所需要做的就是更改以下內容:

elements = []
elements.append(range(0,6))

進入

elements = range(0,6)

您將獲得預期的結果

為什么

首次創建elements時,它是一個空白列表。 然后將range(0,6)附加到空列表。 現在元素看起來像[[0,1,2,3,4,5]] (或[range(0,6)] ),它是一個包含一個元素的列表,一個列表。

這是因為elements包含一個element ,即一個list[0, 1, 2, 3, 4, 5] list.append()將一個項目添加到列表的末尾。

In [1]: elements = []

In [2]: elements.append(range(0,6))

In [3]: elements
Out[3]: [[0, 1, 2, 3, 4, 5]]

也許您打算擴展此列表:

In [1]: elements = []

In [2]: elements.extend(range(0, 6))

In [3]: elements
Out[3]: [0, 1, 2, 3, 4, 5]

還是更換它?

In [4]: elements = range(0,6)

In [5]: elements
Out[5]: [0, 1, 2, 3, 4, 5]

甚至:

In [6]: elements = [element for element in range(0,6)]

In [7]: elements
Out[7]: [0, 1, 2, 3, 4, 5]

在此示例中, 列表理解是不必要的,但它演示了如何輕松過濾或映射這些元素。

.append將單個元素添加到列表中。 那個元素是range(0, 6) 0,6 range(0, 6) ,它是[0, 1, 2, 3, 4, 5] (Johnsyweb在我之前得到了它)。 您可以使用.extend追加每個

elements = []


elements.append(range(0,6)) 
# appends range(0,6) to elements. range(0,6) creates a list in Python 2.x but only in Python 2.x. thanks to adsmith for pointing this out.

print elements

[[0, 1, 2, 3, 4, 5]] # it's clear that elements has 1 element. A list.

這就是為什么

for i in elements:
    print "adding %s to elements" % i

產生:

adding [0,1,2,3,4,5] to elements

要獲得所需的輸出:

elements = range(0,6)

要么

elements = [i for i in range(0,6)] # list comprehension

然后

for i in elements:
    print "adding %s to elements" % i

輸出你想要的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM