我想從我的串列中找到的客戶示例:
{'Customers': [{"Customer's ID": '001', "Customer's Name": 'dor', "Customer's City": 'london', "Customer's age": '26'}, {"Customer's ID": '002', "Customer's Name": 'John Cena', "Customer's City": 'New York', "Customer's age": '45'},{"Customer's ID": '003', "Customer's Name": 'Tony Stark', "Customer's City": 'Holywood', "Customer's age": '39'}]}
我從客戶模塊處理客戶系統的代碼:
def find_customer_by_name(customer_name, customers_library):
"""
A search function that search customer in library by his name
:param customer_name: Customer's name'
:param customers_library: a dict with all customers in the library
"""
customers_temp_library = copy.deepcopy(customers_library)
if customer_name in customers_temp_library["Customers"][0]["Customer's Name"]:
return f"{customer_name} is in the customers library list"
主要代碼:
if identifier == '3': # Choosing to find customer (by name)
print("Enter customer's name you would like to find: ")
customer_name = input()
print(find_customer_by_name(customer_name, customers_library))
uj5u.com熱心網友回復:
由于您沒有使用迭代程序來檢查所有記錄,因此以下修改使用回圈來檢查所有記錄是否提供了客戶名稱
def find_customer_by_name(customer_name, customers_library):
"""
A search function that search customer in library by his name
:param customer_name: Customer's name'
:param customers_library: a dict with all customers in the library
"""
customers_temp_library = copy.deepcopy(customers_library)
for i in range(len(customers_temp_library["Customers"])):
if customer_name in customers_temp_library["Customers"][i]["Customer's Name"]:
return f"{customer_name} is in the customers library list"
由于您沒有修改資料,因此可以通過洗掉副本來遵循優化的代碼形式,因此僅迭代集合并檢查所需的名稱是安全的
data = {'Customers': [{"Customer's ID": '001', "Customer's Name": 'dor', "Customer's City": 'london', "Customer's age": '26'}, {"Customer's ID": '002', "Customer's Name": 'John Cena', "Customer's City": 'New York', "Customer's age": '45'},{"Customer's ID": '003', "Customer's Name": 'Tony Stark', "Customer's City": 'Holywood', "Customer's age": '39'}]}
def find_customer_by_name(customer_name, customers_library):
"""
A search function that search customer in library by his name
:param customer_name: Customer's name'
:param customers_library: a dict with all customers in the library
"""
for customer in customers_library["Customers"]:
if customer_name == customer["Customer's Name"]:
return f"{customer_name} is in the customers library list"
return f"{customer_name} is not in the list"
test = ['Tony Stark', 'Foo', 'Bar', 'John Cena']
for name in test:
print(find_customer_by_name(name, data))
輸出如下

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389959.html
上一篇:從熊貓資料框中的字典串列中提取值
