我尝试用python编写购物程序。因此,我需要将购物商品归类为用户添加的默认商品或新商品,如下所示: 1-用户可以添加类别和项目,也可以对其进行更新。
shop = [category1[ [item name : apple , count : 2 , price:1$],[item name :orange , count :2 , price:3]],category2[[item name : spoon , count :2 , price :3],[item name :fork , count :4 , price:5]]]
答案 0 :(得分:0)
使用dictionary作为数据可能会更好:
shop = {
'category1': {
'apple': { 'count': 2, 'price': 1 },
'orange': { 'count': 2, 'price': 3 }
},
'category2': {
'spoon': { 'count': 2, 'price': 3 },
'fork': { 'count': 4, 'price': 5 }
}
}
如果需要,您仍然可以遍历键,并且它提供了明智的嵌套,因为您可以访问命名键而不是索引。