2014-09-02 48 views
2
def f(a): 
    for i in a: 
     print i 
>>> f(i for i in [1,2,3]) 
1 
2 
3 
>>> f([i for i in [1,2,3]]) 
1 
2 
3 
>>> f((i for i in (1,))) 
1 

我在第一個例子中通過了一個tupple或列表嗎?作爲參數傳遞給函數的實際內容是什麼?

它們之間有什麼不同?

+0

您傳遞了一個生成器。嘗試將'print type(a)'行添加到你的函數中。 – 2014-09-02 05:48:00

+0

迭代列表中的每個元素 – Nabin 2014-09-02 05:48:48

回答

2

你傳遞一個發電機和一個列表:

>>> def f(a): 
...  print type(a) 
...  for i in a: 
...   print i 
... 
>>> f(i for i in [1,2,3]) 
<type 'generator'> 
1 
2 
3 
>>> 
>>> f([i for i in [1,2,3]]) 
<type 'list'> 
1 
2 
3 
>>> f((i for i in (1,))) 
<type 'generator'> 
1 
>>> 

兩者都是可迭代的for循環,但它的工作方式不同。生成器每次迭代執行一個語句,並且列表(或另一個Iterables)是一段​​數據,它的所有元素都不存在任何操作。
關於生成器的更多信息here

0

您並不是真的想要檢查類型,因爲您會打敗多態的目的。但是,如果您確實想知道該對象的類型,則可以調用內置的type()函數。

#Python 3.x 
a=[1,2,3] 
b=(1,2,3) 
type(a) 
<class 'list'> 
type(b) 
<class 'tuple'> 
相關問題