2013-05-30 155 views
1

問題是在不使用len(list)的情況下對列表中的元素進行計數。統計列表中的元素

我的代碼:

def countFruits(crops): 
    count = 0 
    for fruit in crops: 
    count = count + fruit 
    return count 

錯誤是:「詮釋」和「海峽」

這些都應該是要運行的程序的測試案例。

crops = ['apple', 'apple', 'orange', 'strawberry', 'banana','strawberry', 'apple'] 
count = countFruits(crops) 
print count 
7 
+0

在第一時間通過你的for循環,你問的Python添加'0'和''apple''。 Python不知道如何做到這一點,所以會引發錯誤。你能做到這一點,所以你只是在一起添加數字嗎? –

+0

'count = count + 1'或簡單地'count + = 1' – root

+1

'count = crop .__ len __()'?. (除非你認爲這是作弊:D) – kampu

回答

1

試試這個:

def countFruits(crops): 
    count = 0 
    for fruit in crops: 
    count = count + 1 
    return count 

要計算你只需要添加1對發現櫃檯的每個元素,忽略fruit列表的長度。或者,您可以編寫符合加入這樣的:

count += 1 

而且因爲我們沒有實際使用fruit,我們可以寫出for這樣的:

for _ in crops: 

使得無論修改,這裏是實現的最終版本:

def countFruits(crops): 
    count = 0 
    for _ in crops: 
     count += 1 
    return count 
1

您需要簡單地替換錯誤的表達式:count = count + fruit

def countFruits(crops): 
    count = 0 
    for fruit in crops: 
    count += 1 
    return count 

表達式爲x在y中,得到x如何從列表y中獲得對象,可以使用枚舉函數枚舉(crop),返回對象和數量。使用 其他方式:

countFruits = lambda x: x.index(x[-1])+1 

但最好的方法是用LEN(),你可以辭職名稱:

countFruits = len 
1

使用RecursionTernary operator

def count_elements(list_): 
    return 1 + count_elements(list_[1:]) if list_ else 0 

print(count_elements(['apple', 'apple', 'orange', 'strawberry'])) 

輸出:

4 
+1

這是非常無效的,因爲'iterable [1:]'會不斷創建新的列表對象,導致舊列表對象被拋棄(更不用說遞歸本身的開銷)。當您使用* list *訪問時(列表可迭代,但迭代不能是列表),'iterable'也是錯誤的術語。 – poke

+0

@poke:我將'iterable'改爲'list_'。我知道那不是有效的。由於OP不能使用'len',我假設這是一個練習,以便學習python編程。所以我想提出一種使用OP可能不知道的功能的方法(遞歸...),這還沒有提出。 –

1
def count(x): 
    return sum(1 for _ in x) 

以上是相當有效的;在理解之前,理解不會擴展到記憶中,而是積累每個生成的元素。也就是說:sum([1 for _ in x])會更糟。

無法想象爲什麼你不想使用len() ......我可以想象的唯一原因是如果迭代器是一個發生器,你不想吃元素,在這種情況下只需添加一個計數器循環(通過enumerate使得它乾淨,但也許有點隱蔽。

for i, item in enumerate(my_generator): 
    do_stuff(item) 

print 'Did things to {} items'.format(i) 
0

由於len()的使用是被禁止的,我以爲你是接受任務的真正意義是學習Python中的不同技術。

使用高階函數與reduce()lambdalist comprehensions的解決方案 - 所以基本上大部分的蟒蛇好吃的東西...

def countFruits(crops): 
    return reduce(lambda x, y: x+y, [1 for _ in crops]) 

crops = ['apple','orange', 'banana'] 
print countFruits(crops) 
0
def countFruits(crops): 
    return max(enumerate(crops, 1))[0]