问题:只计算星期一和星期二购买的苹果总数。
这是我目前的代码:
apple = 0
banana = 0
orange = 0
#number of fruits bought on monday, tuesday and wendsday respectively
fruit = [ ['apple', 'cherry', 'apple', 'orange'],
['orange', 'apple', 'apple', 'banana'],
['banana', 'apple', 'cherry', 'orange'] ]
for x in fruit:
if 'apple' in x:
if fruit.index(x) == 0 or fruit.index(x) == 2:
apple + 1
print(apple)
由于某种原因,我打印apple
得到的当前结果是0
。
我的代码出了什么问题?
代码中的问题是,你只增加了苹果的数量,但没有将它们分配到任何变量中,这就是为什么它打印它的初始值:
apple = 0
apple + 1
你需要做:
apple += 1
index(x(总是返回该元素第一次出现的索引,即:
fruit[1].index('apple')
将返回"苹果"在果实中首次出现的指数[1],为1。
但根据你的问题,这个解决方案是不正确的,因为他们只在周一和周三询问了没有苹果,所以你需要手动这样做,因为根据你的解决方案,它还将计算周二的苹果,其中"苹果"的索引为0或2。以下是正确的解决方案
apple = 0
banana = 0
orange = 0
#number of fruits bought on monday, tuesday and wendsday respectively
fruit = [ ['apple', 'cherry', 'apple', 'orange'],
['orange', 'apple', 'apple', 'banana'],
['banana', 'apple', 'cherry', 'orange'] ]
apple += fruit[0].count('apple')
apple += fruit[2].count('apple')
print(apple)
您的代码有两个问题。
第一个问题是:
if fruit.index(x) == 0 or fruit.index(x) == 2:
apple + 1
apple + 1
没有做任何有意义的事情。如果你想你需要增加apple
,你需要做apple += 1
。这导致apple
是2
第二个问题是,您需要计算总数,它是3
个苹果,而不是2
个。星期一买了两个苹果,星期三买了一个。
您可以将collections.Counter
用于此
from collections import Counter
for x in fruit:
if 'apple' in x:
if fruit.index(x) == 0 or fruit.index(x) == 2:
apple += Counter(x)['apple']
应该是apple += 1
,而不是apple + 1