python - Calling methods and iterating over list
问题描述
I'm trying to ask for ingredients in a recipe via the input function. I want to store that ingredient in a dictionary, separated by quantity and ingredient. For example, an input of '3 eggs', should yield {'3': 'eggs'}
.
The way i do this is with the separate()
and convert_to_dict()
methods.
I want to ask continuously for the ingredients by means of the input, hence the while True
loop.
Basically, i do this via the following code:
ingredients_list = []
def separate(list):
for i in list:
return re.findall(r'[A-Za-z]+|\d+', i)
def convert_to_dict(list):
i = iter(list)
dct = dict(zip(i, i))
return dct
while True:
ingredient = input("Please input your ingredient: ")
ingredients_list.append(ingredient)
print(convert_to_dict(separate(ingredients_list)))
This works fine, but the only problem with it is that when i input another ingredient, the separate()
and convert_to_dict()
methods only seem to work for the first ingredient in the ingredient list. For example, i firstly input '3 eggs', and then '100 gr of flour', yet it only returns {'3': 'eggs'}
. I'm sure there is something i'm missing, but can't figure out where it goes wrong.
解决方案
I think you've got the idea of your key-value pairs the wrong way around!
Keys are unique. Updating a dictionary with an existing key will just override your value. So if you have 3 eggs, and 3 cups of sugar, how do you envision your data structure capturing this information?
Rather try doing -
{'eggs': 3} # etc.
That should sort out a lot of problems...
But that's all besides the point of your actual bug. You've got a return
in your for-loop in the separate function...This causes the function to return the first value encountered in the loop, and that's it. Once a function's reached a return
in exist the function and returns to the outer scope.
推荐阅读
- rasa - 尽管正确识别了意图,但 RASA 响应始终为空
- linux - awk:根据列组中的最大值过滤文件
- python - FFmpegAudio 和 discord.py,加速音轨
- vue.js - 将 route.params.id 传递给 vuex 操作
- python - 无法安装 zipline 和 TA-lib python 库
- docker - 错误:无法锁定容器上的配置文件错误
- swiftui - SwiftUI ZIndex 动画没有发生
- javascript - 在事件监听器被“点击”之前加载内容
- vue.js - VueJS:编译器错误状态数据属性在通过此属性访问时不存在
- microsoft-dynamics - 如何隐藏动态门户注册表单上的字段