求助大佬
红鲤鱼与绿鲤鱼与驴,到底几条鱼几头驴?计算出列表word = ["红","鲤","鱼","与","绿","鲤","鱼","与","驴"]有几条鱼几头驴。新建一个字典输出结果,格式为:{'鱼': 2, '驴': 1}。
# 定义红鲤鱼与绿鲤鱼与驴列表
word = ["红","鲤","鱼","与","绿","鲤","鱼","与","驴"]
dic={}
num1 = 0
num2 = 0
item1 ="鱼"
item2 ="驴"
for item1 in word:
num1 = num1 + item1
for item2 in word:
num2 = num2 + item2
print(dic)
请问如果按照我这种思路写
应该怎么补全 你写的不对没法通过补全实现
改动最少的写法
word = ["红","鲤","鱼","与","绿","鲤","鱼","与","驴"]
dic={}
num1 = 0
num2 = 0
item1 ="鱼"
item2 ="驴"
for item in word:
if item == item1:
num1 = num1 + 1
dic = num1
for item in word:
if item == item2:
num2 = num2 + 1
dic = num2
print(dic)
word = ["红","鲤","鱼","与","绿","鲤","鱼","与","驴"]
dic={}
num1 = 0
num2 = 0
item1 ="鱼"
item2 ="驴"
for item in word:
if item==item1:
num1+=1
elif item==item2:
num2+=1
dic={item1:num1, item2:num2}
print(dic)
页:
[1]