gpt4 book ai didi

python - 根据列表字典python的输入获取名称

转载 作者:行者123 更新时间:2023-12-05 09:31:05 24 4
gpt4 key购买 nike

根据输入值,我需要得到相应的名称。我有我的输入 my_list,其中包含名称、min_size 和 max_size。如果输入值小于min_size和max_size,我们需要返回对应的name

下面的代码工作正常,但我们可以通过添加任何映射功能来提高性能和可读性吗?

代码

import random
my_list = [
{"name": "bob01", "min_size": 0, "max_size": 100, "capacity": 200},
{"name": "bob02", "min_size": 101, "max_size": 1000, "capacity": 100},
{"name": "bob03", "min_size": 1001, "max_size": 5000, "capacity": 50},
{"name": "bob04", "min_size": 5001, "max_size": 10000, "capacity": 25},
{"name": "bob05", "min_size": 10001, "max_size": 50000, "capacity": 12},
{"name": "bob06", "min_size": 50001, "max_size": 100000, "capacity": 6},
{"name": "bob07", "min_size": 100001, "max_size": 150000, "capacity": 3},
{"name": "bob08", "min_size": "any", "max_size": "any", "capacity": 1}
]
def get_name(n):
for person in my_list:
try:
min = person['min_size']
max = person['max_size']
if min <= n <= max:
return person['name']
except TypeError:
return person['name']

for i in range(10):
n = random.randint(0, 170000)
print("My load is ", n)
name = (get_name(n))
print("Mr {} can handle this load".format(name))

最佳答案

您的代码已经相当高效。我只是建议删除 try except block 以提高效率:

def get_name(n):
for person in my_list:
if isinstance(person['min_size'], int) and isinstance(person['max_size'], int):
if person['min_size'] <= n <= person['max_size']:
return person['name']
else:
return person['name']

关于python - 根据列表字典python的输入获取名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69115580/

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