以下是使用Python實現(xiàn)商品價格區(qū)間設置和排序的示例代碼:
# 商品列表
product_list = [
{'name': '商品A', 'price': 50},
{'name': '商品B', 'price': 80},
{'name': '商品C', 'price': 120},
{'name': '商品D', 'price': 150},
{'name': '商品E', 'price': 200},
{'name': '商品F', 'price': 250},
{'name': '商品G', 'price': 300},
{'name': '商品H', 'price': 350},
{'name': '商品I', 'price': 400},
{'name': '商品J', 'price': 450}
]
# 價格區(qū)間
price_ranges = [
{'min': 0, 'max': 100},
{'min': 101, 'max': 200},
{'min': 201, 'max': 300},
{'min': 301, 'max': 500}
]
# 將商品按價格區(qū)間分類
product_dict = {}
for product in product_list:
for price_range in price_ranges:
if price_range['min'] <= product['price'] <= price_range['max']:
if price_range not in product_dict:
product_dict[price_range] = []
product_dict[price_range].append(product)
break
# 按價格排序并輸出
for price_range in product_dict:
products = product_dict[price_range]
sorted_products = sorted(products, key=lambda x: x['price'])
print('價格區(qū)間:', price_range['min'], '-', price_range['max'])
print('商品列表:')
for product in sorted_products:
print(product['name'], product['price'])
以下是使用Python實現(xiàn)商品價格區(qū)間設置和排序的示例代碼:
python
Copy code
商品列表
product_list = [
{‘name’: ‘商品A’, ‘price’: 50},
{‘name’: ‘商品B’, ‘price’: 80},
{‘name’: ‘商品C’, ‘price’: 120},
{‘name’: ‘商品D’, ‘price’: 150},
{‘name’: ‘商品E’, ‘price’: 200},
{‘name’: ‘商品F’, ‘price’: 250},
{‘name’: ‘商品G’, ‘price’: 300},
{‘name’: ‘商品H’, ‘price’: 350},
{‘name’: ‘商品I’, ‘price’: 400},
{‘name’: ‘商品J’, ‘price’: 450}
]
價格區(qū)間
price_ranges = [
{‘min’: 0, ‘max’: 100},
{‘min’: 101, ‘max’: 200},
{‘min’: 201, ‘max’: 300},
{‘min’: 301, ‘max’: 500}
]
將商品按價格區(qū)間分類
product_dict = {}
for product in product_list:
for price_range in price_ranges:
if price_range[‘min’] <= product[‘price’] <= price_range[‘max’]:
if price_range not in product_dict:
product_dict[price_range] = []
product_dict[price_range].append(product)
break
按價格排序并輸出
for price_range in product_dict:
products = product_dict[price_range]
sorted_products = sorted(products, key=lambda x: x[‘price’])
print(‘價格區(qū)間:’, price_range[‘min’], ‘-’, price_range[‘max’])
print(‘商品列表:’)
for product in sorted_products:
print(product[‘name’], product[‘price’])
在這個示例代碼中,我們定義了商品列表和價格區(qū)間,并使用嵌套的字典將商品按價格區(qū)間分類。然后,對于每個價格區(qū)間,使用sorted函數(shù)對商品列表進行排序,并使用print函數(shù)輸出排序后的商品列表。
在排序時,我們使用了lambda函數(shù)來指定按照商品價格進行排序。lambda函數(shù)是一個匿名函數(shù),可以用于簡單的函數(shù)定義。在這個示例代碼中,lambda函數(shù)接受一個參數(shù)x,并返回x[‘price’],表示按照商品價格進行排序。文章來源:http://www.zghlxwxcb.cn/news/detail-476138.html
最后,運行這段代碼,你將看到每個價格區(qū)間對應的商品列表,并按照價格從低到高進行排序。文章來源地址http://www.zghlxwxcb.cn/news/detail-476138.html
到了這里,關于使用Python實現(xiàn)商品價格區(qū)間設置和排序的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!