python中如何从字典中检索特定数据

2024-04-19 14:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典

product_list = {'Name': ['Milk, 2 Litres', 'Bread', 'Sugar', 'Apple'], 'Price': ['2.0', '3.5', '3.0', '4.5'], 'weight': ['2', '0.6', '2.8', '4.2']} <br/>
Now the Question is <br/>
class Weightcheck:<br/>
    def bag_products(product_list):<br/>
       bag_list = []<br/>
        non_bag_items = []<br/>
        MAX_BAG_WEIGHT = 5.0<br/>

        for product in product_list:
            if product.weight > MAX_BAG_WEIGHT:
                product_list.remove(product)
                non_bag_items.append(product)

每当我把一个参数传递给函数as时

demo = Weightcheck()
demo.bag_products(product_list)

我得到这个错误:

TypeError: bag_products() takes 1 positional argument but 2 were given


Tags: namebr字典demoitemsproductmaxlist
2条回答

您没有在bag_products中添加self。你知道吗

替换

def bag_products(product_list):

def bag_products(self, product_list):

根据评论编辑

product_list = {'Name': ['Milk, 2 Litres', 'Bread', 'Sugar', 'Apple'], 'Price': ['2.0', '3.5', '3.0', '4.5'], 'weight': ['2', '0.6', '2.8', '4.2']}

class Weightcheck:
    def bag_products(self, product_list):
        bag_list = []
        non_bag_items = []
        MAX_BAG_WEIGHT = 5.0

        for w in product_list['weight']:
            if float(w) > MAX_BAG_WEIGHT:
                bag_list.append(w)
                non_bag_items.append(w)
        print(bag_list)
        print(non_bag_items)

demo = Weightcheck()
demo.bag_products(product_list)

使用词典列表应该更好

product_list = [
    {'Name': 'Milk, 2 Litres', 'Price': '2.0', 'weight': '2',},
    {'Name': 'Bread', 'Price': '3.5', 'weight': '0.6'}
]


class Weightcheck:
    def bag_products(self, product_list):
        non_bag_items = []
        MAX_BAG_WEIGHT = 5.0

        for product in product_list:
            if float(product['weight']) > MAX_BAG_WEIGHT:
                product_list.remove(product)
                non_bag_items.append(product)

相关问题 更多 >