簡體   English   中英

計算列表中的元素

[英]count the elements in a list

問題是在不使用len(list)的情況下計算列表中的元素。

我的代碼:

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

錯誤是:'int'和'str'

這些應該是應該運行程序的測試用例。

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

嘗試這個:

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

你需要簡單的替換錯誤的表達式: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

使用RecursionTernary運算符

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

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

輸出:

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

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

無法想象為什么你不想使用len() ...我能想象的唯一原因是如果iterable是一個生成器並且你不想吃元素,在這種情況下只需添加一個計數器循環(通過enumerate使其干凈,但可能有點隱藏。

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

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

由於禁止使用len() ,我假設你給出的任務的真正含義是學習python中的不同技術。

使用具有reduce()lambdalist comprehensions的高階函數的解決方案 - 所以基本上大多數python好東西......

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

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

暫無
暫無

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

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