gpt4 book ai didi

Python 字典更新和细化循环

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:22 25 4
gpt4 key购买 nike

我正在尝试创建一个循环,在原始传递和解析用户字符串后进一步完善用户定义的字典:

product_info = {'make': [], 'year': [], 'color': []}

make = ['honda','bmw','acura']
year = ['2013','2014','2015','2016']
colors = ['black','grey','red','blue']

user_input = raw_input()

for m in make:
if m in user_input:
product_info['make'].append(m)
for y in year:
if y in user_input:
product_info['year'].append(y)
for c in color:
if c in user_input:
product_info['color'].append(c)

在这里,我想检查该字典并确保所有值都已填充,如果没有,则要求更多输入来完善现有字典:

示例:我正在寻找一辆灰色汽车

product_info = {'make': [], 'year': [], 'color': ['grey']}

if product_info['make'] is null:
print 'what make of car are you looking for?'

new_input = 'i am looking for a 2015 honda'

通过字典/解析过程再次发送字符串,并更新product_info字典(如果有需要填写的值),并查看他们这次是否提到了年份,等等......

更新的字典:

product_info = {'make': ['honda'], 'year': ['2015'], 'color': ['grey']}

如何接收请求更多信息的新用户输入并对其进行解析、查找属性并更新现有字典而不修改旧属性?

最佳答案

while [] in product_info.values():
for key in product_info:
if product_info[key] == []:
print("What",key)
user_input = raw_input()
for each in user_input.split(' '):
if each in make:
key = 'make'
product_info[key].append(each)
elif each in year:
key = 'year'
product_info[key].append(each)
elif each in colors:
key = 'color'
product_info[key].append(each)

这个非常粗糙的工作系统,您可以对其进行改进,但这取决于您。

关于Python 字典更新和细化循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39279782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com